Top 1 Record Of A Group Of Records
Aug 14, 2007
Hi all, I am relatively new to sql and have an issue I am trying to solve. I have a table with several records with the same id:
id amount date
-- ------ ------
1 100 01/01/2006
1 2000 06/01/2005
2 200 01/01/2005
2 500 06/01/2007
how would I get the data for the record with the newest date?
So I would return:
id amount date
-- ------ ----------
1 100 01/01/2006
2 500 06/01/2007
Thanks in advance for the help.
View 8 Replies
ADVERTISEMENT
Oct 1, 2007
Looking to see if thier is a better way to find the last record entered in a group of records.
What I'm doing now is finding the max for the secound column and then doing a sub query to find the max of the third column having the second columns equal.
Table example using simplied data.
PolId
CoveragId
EffDate
Status
Limit1
2
1
9/7/2007
a
10000
2
2
9/7/2007
a
150000
2
2
10/1/2007
a
200000
3
1
9/7/2007
a
10000
The parent program addes a row every time the data is changed. To make things worst; the records arn't always in sqenal order like the above table and some time edits the row instead.
The current query returns a single value. from a single table.
Current code used in the select protion on a larger query. bpi = basicpolicyInformation.
( Select c1.limit1
From AFW_Coverage as c1
Where c1.PolId=bpi.PolId
and c1.CoverageId = (select max(CoverageId) as CoverageId
From AFW_Coverage as c
where c.PolId = c1.PolId
and c.CoverageCode = 'Dwelling'
and status <> 'D'
)
and c1.effDate = (select max(Effdate) as Effdate
From AFW_Coverage as c
where c.PolId = c1.PolId
and c.CoverageID = c1.CoverageId
)
Explain the current code. It uses the two sub queries to find the correct record ID that has the data needed.
View 16 Replies
View Related
May 21, 2002
Is there a way to do this.
If I have a sorting which gives me multiples of column C1 but which can be uniquely identified by C1+C2+C3, and I want to query for the first C1 in each of C1's unique values, how would I go about doing that?
View 1 Replies
View Related
Sep 16, 2004
Hello Guyz,
A small problem here, I have the below table and I need to group and display the record that has the minimum value in the table (this table is derived from a query that permutates some records to give me this result).
F1 F2 F3
QQQ C 2
QQQ B 1
QQQ A 3
expected result:
QQQ B 1
my result:
when I group by F1, First(F2) and MIN(F3):
QQQ C 1
when I group by F1, MIN(F2) and MIN(F3):
QQQ A 1
when I group by F1, F2 and MIN(F3):
QQQ C 2
QQQ B 1
QQQ A 3
Any help would be very much appreciated..
Cyherus
View 1 Replies
View Related
Dec 14, 2014
I have following query
Select Date, Item_Code, SUM(In_Quantity) as In_Quantity, SUM(Issue_Quantity) as Issue_Quantity, (SUM(In_Quantity)-SUM(issue_Quantity)) as BalanceQty from
(
select tbl_add_product.Date as Date, tbl_add_product.Item_Code, tbl_add_product.In_Quantity, 0 as Issue_Quantity from tbl_add_product
where Item_Code = 'pen'
union ALL
select tbl_issue_product.Date as Date, tbl_issue_product.Item_Code, 0 as In_Quantity, Issue_Quantity from tbl_issue_product
where Item_Code = 'pen'
)
X group by Item_Code, Date
which gives following result:
**Date Item_Code In_Quantity Issue_Quanitity BalanceQty**
2014-12-02 pen 100 0 100
2014-12-03 pen 50 50 0
I want to 100 in second row. the logic is that balance Qty from first row should be added to In_Qty so that when Issue_Quantity is subtracted from it, it gives BalanceQty
View 1 Replies
View Related
Feb 19, 2006
Master,
How can I get the first record of each group which I had selected by "Group by".I try it but failed.3ks
"USE pubs
SELECT top 1 *
FROM titles
GROUP BY type
ORDER BY price"
View 2 Replies
View Related
Feb 28, 2007
Greetings anyone -
I have been attempting to figure out - in Report Builder - how to print only the last record in each group, i.e. the last activity. I see no Last function available anywhere.
Would someone please be so kind as to advise how this can be done?
If this cannot be accomplished in Rpt Builder, it looks as if the Last function is available within Report Designer. Unfortunately, although documentation states it's available, it does not state where this function can be utilized. I'm certainly having no luck.
Help pls?
Tks & B/R
View 1 Replies
View Related
May 18, 2012
query to show last record/Partner or PartnerName.
select 'PURCHASE' as EntityName, d.PartnerName, h.*
from (
select MAX([TimeStamp]) [Data import], COUNT(1) [Numar de inregistrari], StartDate, EndDate, DistributorId
from DataImport.PurchaseHistory
group by DistributorId, StartDate, EndDate
) h
inner join Partner d on d.PartnerId = h.DistributorId
where d.Active = 1
order by DistributorId, StartDate desc, EndDate desc
View 4 Replies
View Related
Jan 24, 2004
I'm looking for some sql syntax that will return the last entry per group in a secondary table. MEANING: have 2 tables, one with names and the other with visits. I need to be able to display all the patients with there last visits.
TABLE1 info
ID1 fname1 lname1 DOB1
ID2 fname2 lname2 DOB2
ID3 fname3 lname3 DOB3
TABLE2 info
ID1 Visit2
ID1 Visit3
ID1 Visit1
ID1 Visit4
ID2 Visit1
ID2 Visit2
ID3 Visit1
I need a view or SP to return the following:
ID1 fname1 lname1 dob1 visit4
ID2 fname2 lname2 dob2 visit2
ID3 fname3 lname3 dob3 visit1
It seems like it should be a smiple process, only I just can't get the syntax to work.... Any Help would be GREAT!
thx
View 2 Replies
View Related
Aug 8, 2013
Here's what I'm trying to do
TransIDMemberIDFundIDBuyPriceDate
1501101$1042013-01-24
2501102$1012013-04-23
3501102$1182013-02-04
4501102$982013-05-19
5501103$532013-05-21
6501103$392013-07-09
I'm trying to get the latest buy price for each fund a member bought.
So in the above example, I'm trying to formulate a query to retrieve all the latest bought price for memberid 105:
Desire Query Result
TransIDMemberIDFundIDBuyPriceDate
1501101$1042013-01-24
4501102$982013-05-19
6501103$392013-07-09
So far, I've tried using Group By clause on FundID and BuyPrice and MAX() function for the date, but I can' get the TransID.
View 3 Replies
View Related
Jan 21, 2014
I have for example a table with columns name, surname, id, ..., weight, age. I need to choose from each age group (GROUP BY age) entire record of the person who has the greatest weight. How to construct such a query?
View 1 Replies
View Related
Mar 18, 2015
I’m writing a document management system. The documents themselves are created from the contents of a database. The database is SQL Server.
The database contains a table, like so:
ClientID, ProjectID, DocumentID, MinorVersion, MajorVersion, Name
Initially, the user will create a “V0.1” document. So the data would look something like
ClientID = 1
ProjectID = 1
DocumentID = 1
MajorVersion = 0
MinorVersion = 1
Name = “My Document”
Thereafter, the user can create new versions as “0.2”, “0.3”, etc., or “1.0”, “1.1”, “2.0”, etc.
For example, a “2.1” document would be stored as:
ClientID = 1
ProjectID = 1
DocumentID = 1
MajorVersion = 2
MinorVersion = 1
Name = “My Document”
The earlier versions will still exist on the database, but the latest version will be 2.1.
There may be several different documents, with different DocumentID’s (e.g. DocumentID = “1”, DocumentID = “2”), etc., and each of these documents may have many versions.
I’m trying to write a query to display a list of documents showing ClientID, ProjectID, DocumentID, MinorVersion, MajorVersion, Name… but the list should only display the latest version of each document.
So, if the database contained the following records:
ClientID, ProjectID, DocumentID, MajorVersion, MinorVersion, Name
1,1,1,0,1,My Document
1,1,1,0,2,My Document
1,1,1,0,3,My Document
1,1,1,1,0,My Document
1,1,1,2,0,My Document
1,1,1,2,1,My Document
1,1,2,0,1,My Second Document
1,1,2,0,2,My Second Document
1,1,2,0,3,My Second Document
My query should return:
ClientID, ProjectID, DocumentID, MajorVersion, MinorVersion, Name
1,1,1,2,1,My Document
1,1,2,0,3,My Document
… where 2.1 is the latest version of Document 1 and 0.3 is the latest version of Document 2.how to do it.
View 4 Replies
View Related
May 30, 2006
Hendra writes "I'd like to know is there any way or any statement that can help me to get first or last record from the group by query ?
I'm using sql Server 2000
Thank's
_Hendra_"
View 1 Replies
View Related
Jun 22, 2007
I have a set of timecard records with a projectNumber, taskNumber and TimeCardHours:
Rec# projectNumbeer taskNumber Employee timeCardHours
1 123 1.01.Test1 John 4
2 123 1.01.Test1 John 6
3 123 1.99.Test3 Mary 8
4 123 1.02.Test5 Mary 4
5 123 1.06.Test6 Mary 4
6 123 1.08.xyz5 Mary 6
7 123 1.03.xyz7 Jane 8
8 123 1.01.xyz4 Jane 5
9 123 1.04.xyz7 Jane 3
10 123 1.05.Test6 Mary 4
11 123 1.07.Test6 Mary 4
I have the following fixed set of tasks:
taskID taskNumberPrefix Task Description phaseID
11.01 Planning1
21.02 Design2
31.03 Requirements2
41.04 Coding3
51.05 Testing4
61.06 Build3
71.07 Packaging3
81.08 Documentation5
91.99 Management1
Finally, I have different phases:
1Planning
2Analysis
3Development
4Testing
5Documentation
What I would like to do is obtain a summary of timecard hours for each phase.
So for example, in Phase 1, Planning, this has two tasks based on PhaseID=1, Planning and Management which have task number prefixes of 1.01 and 1.99 respectively.
What I would like to is sum all the timecard records are LIKE 1.01% or 1.99% so my final results based on the above data would provide the phase name and total hours.
Planning Phase total Hours
Planning 23 (Sum of records 1,2,3,8)
Analysis 12 (Sum of records 4,7)
Coding 8 (Sum of records 5,9,11)
Testing 4 (Sum of record 10)
Documentation 6 (Sum of record 6)
I have tried various select statements, but helps up when I want to have TaskNumberPrefix LIKE taskNumber%.
Thanks for any assistance.
View 4 Replies
View Related
Sep 18, 2006
I have a question about selecting only the first record in a group. Example: I have table A with primary key = 999. Table B has multiple records with primary key = 999. How can I match Table A 999 with the first occurrence of 999 in Table B, and then extract other field data (such as street address) from the Table B record. I have tried using the Count() function, but it seems that I can only do this using cursors.
Thanks,
BobD
View 2 Replies
View Related
Jun 12, 2006
I have a table as shows here:
col1 col2
1 rec1 *
2 rec1
3 rec1
4 rec2 *
5 rec2
6 rec2
and now I need to update the field col1 of the first records with
different col2 value. that means I need to update the col1 filed of the
* marked record.
any suggestion about how to do it with SQL server 2000?
thanks a lot.
View 1 Replies
View Related
Aug 3, 2015
I would like to display all the products with maximum SeqNo from the table below:
TABLE
ProductIDSeqNoBalance
111215
11135
111420
111510
12115
1212100
121325
121445
OUTPUT
ProductIDSeqNoBalance
111510
121445
View 3 Replies
View Related
Feb 25, 2015
Here is some sample data:
CREATE TABLE
#MyTable
(
Pk INT,
GroupID INT,
Value VARCHAR(10)
[code]...
I am looking to retrieve any GroupID in which every Value of that GroupID is either (a) null, (b) an empty string, or (c) "XYZ". So in the above example, GroupID #1 would not be returned in my query because there is a Value of "ABC", but GroupID #2 would be returned since it consists of only nulls, "XYZ"'s, and empty strings.What would be the most efficient way to write such a query?
View 2 Replies
View Related
May 13, 2007
Hello
I have a table from cars GPS positions:
CREATE TABLE Positions (
Ident VARCHAR(20) NOT NULL,
Valid BOOL,
Date DATETIME NOT NULL,
Latitude FLOAT,
Longitude FLOAT,
Speed INT
}
Sorry about the poor english... :)
I like select the last position where Ident=DEMO1 and DEMO2....
How can I make that?
Practically I sould like to now, where is the last positions of selected cars!
I try this, but not good:
SELECT
MAX(date),
ident,
latitude,
longitude,
speed
FROM
positions
WHERE
valid=1 &&
(ident='DEMO1' || ident='DEMO2'|| ident='DEMO3')
GROUP BY
ident
;
I get 3 record, the dates is the last, but the lat. and long. is wrong...
Thanks,
Laci
View 5 Replies
View Related
Oct 12, 2007
How to get
Code Block
a record value instead of aggregated value with GROUP BY?
Assume that I have a PRODUCT_COMMENT table defined as below. It logs
the multiple comments for products. A product may have multiple
comments logged at different time.
Code Block
CREATE TABLE [dbo].[PRODUCT_COMMENT](
[COMMENT_ID] [int] IDENTITY(1,1) NOT NULL,
[PRODUCT_ID] [int] NOT NULL,
[COMMENT] [nvarchar](50) NULL,
[UPDATED_ON] [datetime] NOT NULL,
CONSTRAINT [PK_PRODUCT_COMMENT] PRIMARY KEY CLUSTERED
(
[COMMENT_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY
= OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PRODUCT_COMMENT] WITH CHECK ADD CONSTRAINT
[FK_PRODUCT_COMMENT_PRODUCT] FOREIGN KEY([PRODUCT_ID])
REFERENCES [dbo].[PRODUCT] ([PRODUCT_ID])
GO
ALTER TABLE [dbo].[PRODUCT_COMMENT] CHECK CONSTRAINT
[FK_PRODUCT_COMMENT_PRODUCT]
I would like to use the following SQL statement to get the latest
comments for all products.
Code Block
SELECT PRODUCT_ID, COMMENT, UPDATED_ON
FROM PRODUCT_COMMENT
GROUP BY PRODUCT_ID
HAVING UPDATED_ON = MAX(UPDATED_ON)
But this leads to the following error:
Code Block
Column 'PRODUCT_COMMENT.UPDATED_ON' is invalid in the HAVING clause
because it is not contained in either an aggregate function or the
GROUP BY clause.
Is there a way to do that?
Thanks!
View 5 Replies
View Related
Apr 12, 2015
I have a table with records like that.
Group | Value
Team 1 | 0
Team 1 | 0
Team 1 | 1
Team 1 | 1
Team 2 | 0
Team 2 | 0
Team 2 | 0
I want a script that return 0 if all the values of the group are 0 and return 1 if the records of the value is mixed with 0 and 1.
View 1 Replies
View Related
Dec 10, 2014
This my table named myData
CREATE TABLE [dbo].[myData](
[idx] [int] NULL,
[paymentMethod] [nvarchar](200) NULL,
[daerahKutipan] [int] NULL,
[payer] [int] NULL,
[code]....
I want to calculate the number of payer Group By paymentMethod. The number of payer must be divided by daerahKutipan. So far, my query as follow
select paymentMethod,
COUNT(CASE WHEN daerahKutipan = 1 THEN payer ELSE 0 END) figure_Seremban,
COUNT(CASE WHEN daerahKutipan = 3 THEN payer ELSE 0 END) figure_KualaPilah,
COUNT(CASE WHEN daerahKutipan = 4 THEN payer ELSE 0 END) figure_PortDickson,
COUNT(CASE WHEN daerahKutipan = 5 THEN payer ELSE 0 END) figure_Jelebu,
COUNT(CASE WHEN daerahKutipan = 6 THEN payer ELSE 0 END) figure_Tampin,
COUNT(CASE WHEN daerahKutipan = 7 THEN payer ELSE 0 END) figure_Rembau,
[code]....
View 1 Replies
View Related
Feb 11, 2012
I have a group of records like this;
NAME| RUN START| RUN END| LK1| LK2| DESC
Graeme Brown|2012-02-23 07:20:00|2012-02-23 07:50:00|2213|2244|AK1/4/PI2
Graeme Brown|2012-02-23 08:00:00|2012-02-23 09:25:00|2244|2052|AK1/4/PI2
Graeme Brown|2012-02-23 09:30:00|2012-02-23 11:05:00|2052|917|AK1/4/PI2
Graeme Brown|2012-02-23 12:15:00|2012-02-23 13:55:00|917|2052|AK1/4/PI2
Graeme Brown|2012-02-23 14:05:00|2012-02-23 15:40:00|2052|1111|AK1/4/PI2
They are grouped on the last column [DESC].
I want to get;
NAME| RUN START| RUN END| LK1| LK2| DESC
Graeme Brown| 2012-02-23 07:20:00| 2012-02-23 15:40:00| 2213| 1111| AK1/4/PI2
So what it needs to do is combine the ;
earliest RUN START and corresponding LK1 with
latest RUN END and corresponding LK2.
I've tried creating temp tables with the mins and maxs - but then I can't combine them with the LK1 and Lk2 fields...
View 3 Replies
View Related
Jun 21, 2007
sample query results:
cid cno cvalue
--- --- -------
835201add edit
835201add edit
836202with VAT
836202with VAT
how can i filter this more into this:
835201add edit
836202with VAT
View 3 Replies
View Related
Nov 7, 2007
Hi,
can anyone help me to group by Top 2 records by ID and Date?
My table contains following data
create table #test (id int, code varchar(10),TestDate datetime)
insert into #test (id,code,TestDate) values (12,'ABC','01/11/2007')
insert into #test (id,code,TestDate) values (12,'ABC','01/11/2007')
insert into #test (id,code,TestDate) values (12,'BC','02/18/2007')
insert into #test (id,code,TestDate) values (12,'BC','02/18/2007')
insert into #test (id,code,TestDate) values (12,'BC12','10/01/2007')
insert into #test (id,code,TestDate) values (12,'BC11','10/11/2007')
insert into #test (id,code,TestDate) values (12,'BC11','01/25/2007')
insert into #test (id,code,TestDate) values (12,'ABC','01/11/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/11/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/12/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/12/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/11/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/11/2007')
select * from #test order by TestDate
--Result Set
id code TestDate
12 ABC 2007-01-11 00:00:00.000
12 ABC 2007-01-11 00:00:00.000
12 ABC 2007-01-11 00:00:00.000
12 BC11 2007-01-25 00:00:00.000
14 YZ123 2007-02-11 00:00:00.000
14 YZ123 2007-02-11 00:00:00.000
14 YZ123 2007-02-11 00:00:00.000
14 YZ123 2007-02-12 00:00:00.000
14 YZ123 2007-02-12 00:00:00.000
12 BC 2007-02-18 00:00:00.000
12 BC 2007-02-18 00:00:00.000
12 BC12 2007-10-01 00:00:00.000
12 BC11 2007-10-11 00:00:00.000
--I want to get only duplicate records, so SQL should eliminate uniq recod.Total will --get total number of records per ID and date, but want to display only two reacords by --Id and Testdate.
--my result set should contain following data
--Total of first byID and by Date
----id code TestDate Total
----12 ABC 2007-01-11 00:00:00.000 3
----12 ABC 2007-01-11 00:00:00.000
----14 YZ123 2007-02-11 00:00:00.000 3
----14 YZ123 2007-02-11 00:00:00.000
----14 YZ123 2007-02-12 00:00:00.000 2
----14 YZ123 2007-02-12 00:00:00.000
----12 BC 2007-02-18 00:00:00.000 2
----12 BC 2007-02-18 00:00:00.000
If anyone have any idea,, plz help me out..
Thanks....
View 2 Replies
View Related
Aug 11, 2015
I have a table where I am grouping on one field and would like an individual (separate) count of values from another field of same table. So for example, I have following data:
instance_id, area, values
101 North 1
102 North 2
103 East 2
104 East 2
I would like to report on Area, and count of rows with different Values types, for example:
Area Value - 1, Value - 2, Value - 3
North 1 1 0
East 0 2 0
I am not sure what the technical term is for such report, but I can group by Area column, and but its aggregating counts on different Value types that I am having difficulty in performing in SSRS.
View 2 Replies
View Related
Dec 20, 2013
1.Create the tables with insert queries
2. provide the result as required in an temp table
3. Display the expected result
======================================================================
CREATE TABLE and Insert Data
======================================================================
use master
CREATE TABLE [dbo].[Travel_Master](
[Load_Id] [int] NULL,
[Mode_Id] [nchar](2) NULL,
[Mode_Info] [nchar](10) NULL,
[Has_Nodes] [nchar](3) NULL
) ON [PRIMARY]
[Code] .....
View 14 Replies
View Related
Feb 11, 2015
Here is my table data:
CREATE TABLE
#TestTable (
Pk INT,
GroupID INT,
Enabled BIT
[code]..
I need to write a select query that will retrieve any GroupID in which every record has an Enabled value of 1.In the example I've provided, only GroupID 1 and 3 will be returned since GroupID 2 has a record with an Enabled value of 0.What would be the most efficient way to write such a query?
View 2 Replies
View Related
Apr 21, 2006
Hi,
I've a problem with the following stored procedure Select . It does compile and run, but doesn't return the sorted result I wanted, which was to have the records from tblPieces (alias Pcs) sorted by (in order) Pcs.fkBatchId, Pcs.fkProfileCode, Pcs.Colour. What happens instead, I think, is that the correct records are selected, but in the record creation order. CREATE PROCEDURE dbo.LoadOneBatch
(
@BatchId int, -- the pkBatchId of the batch required
@OnlyNew bit -- If true, only consider batches that haven't ever been loaded.
)
AS
SET NOCOUNT OFF
SELECT Bat.pkBatchId,
Pcs.*
FROM tblBatches AS Bat
JOIN (
SELECT Bat1.pkBatchId,
Pcs1.fkProfileCode,
Pcs1.Colour
FROM tblBatches AS Bat1
JOIN tblPieces AS Pcs1 ON Pcs1.fkBatchId = Bat1.pkBatchId
WHERE Bat1.pkBatchId = @BatchId
GROUP BY Bat1.pkBatchId, Pcs1.fkProfileCode, Pcs1.Colour
) SubQ ON SubQ.pkBatchId = Bat.pkBatchId
JOIN tblPieces AS Pcs ON Pcs.fkBatchId = Bat.pkBatchId
WHERE (@OnlyNew = 1 And Bat.IsLoaded = 0 And
Bat.IsCompleted = 0 And Bat.pkBatchId = @BatchId) Or
(@OnlyNew = 0 And Bat.pkBatchId = @BatchId)
GO
EXEC LoadOneBatch @BatchId = 1, @OnlyNew = 0
The DDL for the two tables is:CREATE TABLE [tblBatches](
[Stamp] timestamp NOT NULL,
[pkBatchId] int IDENTITY(1,1) NOT NULL,
[BatchNo] varchar(50) NULL,
[SubmitTime] [datetime] NULL,
[FinishTime] [datetime] NULL,
[IsLoaded] bit NULL,
[IsCompleted] bit NULL,
PRIMARY KEY ( [pkBatchId] ASC )
)
CREATE TABLE [tblPieces](
[Stamp] timestamp NOT NULL,
[pkPieceId] int IDENTITY(1,1) NOT NULL,
[fkBarId] int NULL,
[fkBatchId] int NULL,
[PieceNo] varchar(12) NOT NULL,
[Descrip] varchar(48) NULL,
[Position] real NULL,
[LeadPrep] char(1) NOT NULL,
[TailPrep] char(1) NOT NULL,
[Length] real NOT NULL,
[fkProfileCode] varchar(10) NOT NULL,
[Colour] varchar(5) NOT NULL,
PRIMARY KEY ( [pkPieceId] ASC )
)
The data records output are roughly:pkBatchId Stamp pkPieceIdfkBarIdfkBatchIdPieceNo Descrip PositionLeadPrepTailPrepLengthfkProfileCodeColour
1 0x00000000000036B21 NULL1 00000000000118960 /003/F>1 N2NULL / 913 6000 wht
1 0x00000000000036B32 NULL1 00000000000218960 /003/F<1 N2NULL / 913 6000 wht
View 5 Replies
View Related
Mar 4, 2006
My Table
ID,Customer,Type,Date
records
1,XXX,AAA,Date
2,ZZZ,BBB,Date
3,QQQ,BBB,Date
I group them with the following query
Select Source,Count(*) from table where date=month(getdate()) group by Type order by 2 desc
the result looks like that
AAA,1
BBB,2
------------
Also there are another table for this results (Totals)
fields
Type,Quantity
--------------
AAA,45
CCC,76
(attention, there are no BBB record currently in this table)
I want that
the results of the first query goes to Totals table.
what I need like this
Type,Quantity
--------------
AAA,45 + AAA,1
CCC,76
BBB,2
I don't know how to do
if there is a LOOP solution in sql server , I would like to know
thanks in advance
View 6 Replies
View Related
Apr 4, 2015
Problem 1: I have the following table which shows the location of a person at 1 hour intervals
IdEntityIDEntityNameLocationIDTimexdelta
11MickeyClub house03001
21MickeyClub house04001
31MickeyPark05002
41MickeyMinnies Boutique06003
51MickeyMinnies Boutique07003
61MickeyClub house08004
71MickeyClub house09004
81MickeyPark10005
91MickeyClub house11006
The delta increments by +1 every time the location changes.
I would like to return an aggregate grouped by delta as per example below.
EntityNameLocationIDStartTimeEndTime
MickeyClub house03000500
MickeyPark05000600
MickeyMinnies Boutique06000800
MickeyClub house08001000
MickeyPark10001100
MickeyClub house11001200
I am using the following query (which works fine):
select
min(timex) as start_date
,end_date
,entityid
,entityname
,locationid
[code]....
However I would like to not use the delta (it takes effort to calculate and populate it); instead I am wondering if there is any way to calculate it as part / whilst running the query.
Problem 2:I have the following table which shows the location of different people at 1 hour intervals
IdEntityIDEntityNameLocationIDTimexDelta
11MickeyClub house09001
21MickeyClub house10001
31MickeyPark11002
42DonaldClub house09001
52DonaldPark10002
62DonaldPark11002
73GoofyPark09001
83GoofyClub house10002
93GoofyPark11003
I would like to return an aggregate grouped by person and location.
For example
EntityIDEntityNameLocationIDStartTimeEndTime
1MickeyClub house09001100
1MickeyPark11001200
2DonaldClub house09001000
2DonaldPark10001200
3GoofyPark09001000
3GoofyClub house10001100
3GoofyPark11001200
What modifications do I need to the above query (Problem 1)?
View 0 Replies
View Related
Aug 21, 2014
select
DayRank = ROW_NUMBER() OVER(ORDER BY a.datedel DESC),
a.order,a.line,a.datedel,a.recpt,b.status,
b.item,b.t_sup
from historytbl a
inner join order b
on a.order = b.order
and a.line = b.line
and a.status =4
group by a.order,line,a.datedel,a.recpt,b.status,b.item,b.sup
The query is returned the results below.
Rank OrderLineDateDelrecptitemsup
----- -------------------------------
1aaa102014-18-08rc1zzz1231122
2bbb202014-08-08rc2zzz1231122
3ccc302014-04-08rc3zzz1231122
4ddd902014-08-11rc6yyy123333
5eee102014-05-11rc7yyy123333
5fff90 2014-02-11rc8yyy123333
6ggg102014-05-10rc9qqq123444
7hhh502014-04-10rc0qqq123444
8iii102014-04-10rc5rrr123555
However, I want to have the query only show most recent two records for each group of item and sup, please see the results I want below.
Rank OrderLineDateDelrecptitemsup
----- -------------------------------
1aaa102014-18-08rc1zzz1231122
2bbb202014-08-08rc2zzz1231122
4ddd902014-08-11rc6yyy123333
5eee102014-05-11rc7yyy123333
6ggg102014-05-10rc9qqq123444
7hhh502014-04-10rc0qqq123444
View 4 Replies
View Related
Nov 5, 2014
I'm bulk loading employees into an etl table, each employee has a unique ID number, but they have multiple records in the data. Sometimes their name or birthdate will change and I want to identify those records and only insert the newest version into production. I can do this with a series of temp tables, but I'm sure there's a better way. The SQL below updates the etl table with the flag I want to mark the inserts, but it seems convoluted. (Jon's birthday changes, Jane's birthday changes, Bill's gender changes, Amy nothing changes(I handle those inserts later))
DECLARE @Records TABLE(
firstname varchar(50), lastname varchar(50), birthdate date, sex char(1), IDNum varchar(15), moddate date, opflag char(1))
INSERT INTO @Records
VALUES
('JON','SMITH','20000101','M','12345','20140101','I'),
('JON','SMITH','20000101','M','12345','20140201','I'),
[code]....
View 1 Replies
View Related