在SQL Server中选择组的第一个值

时间:2015-08-25 14:02:59

标签: sql-server

我想选择

Date         Store_ID  Item_ID   Start_Q    Sold     Transferred  End_Q
07-31-2015       1        X1         50       20           0         30
07-31-2015       1        X2         30       10           10        10 
08-01-2015       1        X1         30       10           0         20
08-02-2015       1        X1         20       0            10        10  
08-03-2015       1        X2         10       5             0         5 

我想在商店1中选择商品从'20 -7-2015'到'30 -8-2015' 就像那样

Item_ID    Start_Q    Sum_Sold    Sum_Transferred     End_Q
   X1        50          30             10              10  
   X2        30          15             10               5 

3 个答案:

答案 0 :(得分:0)

这是一种方法。如果您使用的是SQL Server 2012或更高版本,则可以使用窗口函数在没有内部选择的情况下执行此操作。

select
  Item_ID,
  (select top 1 Start_Q from Table1 T2 where T2.Item_ID = T1.ItemID order by date asc) as StartQ,
  Sum_Sold,
  Sum_Transferred,
  (select top 1 End_Q from Table1 T2 where T2.Item_ID = T1.Item_ID order by date desc) as End_Q
from
(
  select 
    Item_ID,
    sum(Sold) as Sum_Sold,
    sum(transferred) as Sum_Transferred
  from
    table1
  group by
    Item_ID
) T1

SQL Fiddle

中的示例

答案 1 :(得分:0)

strftime

答案 2 :(得分:0)

使用CROSS APPLY

SQL Fiddle

SELECT
    Item_ID,
    Start_Q = s.Start_Q,
    Sum_Sold = SUM(Sold),
    Sum_Transferred = SUM(Transferred),
    End_Q = e.End_Q
FROM tbl t
CROSS APPLY(
    SELECT TOP 1 Start_Q
    FROM tbl
    WHERE
        Item_ID = t.Item_ID
        AND [Date] BETWEEN '20150720' AND '20150830'
    ORDER BY [Date] ASC
)s
CROSS APPLY(
    SELECT TOP 1 End_Q
    FROM tbl
    WHERE
        Item_ID = t.Item_ID
        AND [Date] BETWEEN '20150720' AND '20150830'
    ORDER BY [Date] DESC
)e
WHERE
    t.Date BETWEEN '20150720' AND '20150830'
GROUP BY t.Item_ID, s.Start_Q, e.End_Q