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.
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!selectdistinct customerid,--item,transactiondtfrom transactionswhere item in(10014623, 10014653, 10014637, 10014624, 10014641) group by customerid,transactiondtorder bycustomeridtransactiondt 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_transactiondtFROM transactionsWHERE item IN (10014623, 10014653, 10014637, 10014624, 10014641)GROUP BY customeridORDER BY customerid, max_transactiondt |
|
|
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 tblCustWHERE (Item IN (10014623, 10014653, 10014637, 10014624, 10014641, 10014623, 10014653))) t where RN=1Josh |
|
|
|
|
|
|
|