Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Limits...I think

Author  Topic 

kam0002
Starting Member

1 Post

Posted - 2012-09-27 : 13:41:32
So I am trying to pull the first date for each specific ID that I have. I feel like I need a limit, but I need the first result for the date column but I need all ID's returned. This is what I have but am getting an error message about the Limit. But I am very new to this and not sure if a limit is even what I need. Any help would be greatly appreciated!


select
distinct customerid,
--item,
transactiondt

from transactions

where item in
(10014623,
10014653,
10014637,
10014624,
10014641)


group by
customerid,
transactiondt

order by
customerid
transactiondt ASC, (LIMIT 0,1)


*****
some customerid's only have one date, but some have several (ex. customerid 1 might have transactiondt 1/5, 2/7, and 3/12 but I just need the 1/5 returned)

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-09-27 : 14:02:02
If you need to get only those two columns, you can use the MAX (or MIN or another aggregate function) as shown below. If you needed to get other columns, we will have to use a different approach:
SELECT customerid,
--item,
MAX(transactiondt) AS max_transactiondt
FROM transactions
WHERE item IN (10014623, 10014653, 10014637, 10014624, 10014641)
GROUP BY
customerid
ORDER BY
customerid,
max_transactiondt
Go to Top of Page

joshua_caleb
Starting Member

3 Posts

Posted - 2012-09-28 : 04:52:07
Use this method if you need to list all columns. The transaction dates can be ordered in ascending or descending order to get the earliest or latest date.

select * FROM (SELECT CustomerID, Item, Transactiondt, RN =ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY Transactiondt ASC)
FROM tblCust
WHERE (Item IN (10014623, 10014653, 10014637, 10014624, 10014641, 10014623, 10014653))
) t where RN=1


Josh
Go to Top of Page
   

- Advertisement -