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 |
|
Mike_h
Starting Member
7 Posts |
Posted - 2010-03-22 : 03:35:56
|
| I have an order table that has values similar to the ones below.the first field is an order id. I am trying to write a select statement that will take the first record of each order based on the earliest date and output the results of that line but also doing a sum of the last two fields which are order value and linesOrder id cust Note Date Value Lines0539071 CBN cust1 Urgent 180310 1008.80 1140539071 BC cust1 190310 19.96 10539072 CBN cust2 180310 1271.08 200539072 S1 cust2 190310 79.92 1I require the output to look like soOrder id cust Note Date Value Lines0539071 CBN cust1 Urgent 180310 1028.76 1150539072 CBN cust2 180310 1351.00 21Any help would be greatly appreciated.Thanks |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2010-03-22 : 05:09:45
|
[code]DECLARE @sample TABLE( [Order id] varchar(10), [cust] varchar(5), [Note] varchar(15), [Date] int, [Value] decimal(10,2), [Lines] int)INSERT INTO @sampleSELECT '0539071', 'CBN', 'cust1 Urgent', 180310, 1008.80, 114 UNION ALLSELECT '0539071', 'BC', 'cust1', 190310, 19.96, 1 UNION ALLSELECT '0539072', 'CBN', 'cust2', 180310, 1271.08, 20 UNION ALLSELECT '0539072', 'S1', 'cust2', 190310, 79.92, 1SELECT a.[Order id], a.[cust], a.[Note], a.[Date], a.TotValue, a.TotLinesFROM( SELECT *, row_no = row_number() OVER (PARTITION BY [Order id] ORDER BY [Date]), TotValue = SUM(Value) OVER (PARTITION BY [Order id]), TotLines = SUM(Lines) OVER (PARTITION BY [Order id]) FROM @sample) aWHERE a.row_no = 1/*Order id cust Note Date TotValue TotLines ---------- ----- --------------- ----------- ---------------------------------------- ----------- 0539071 CBN cust1 Urgent 180310 1028.76 1150539072 CBN cust2 180310 1351.00 21(2 row(s) affected)*/[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
|
|
|
|
|