我有这样的数据:
DATE ID weight
---- ---- -------
2017-04-25 11:05:42.273 247 0.418
2017-04-25 11:05:42.310 248 0.568
2017-04-25 13:57:55.327 247 0.418
2017-04-25 13:57:55.360 247 0.534
2017-04-25 13:57:55.397 248 0.568
2017-04-25 13:57:55.453 248 0.448
现在要求是我必须根据具有最小日期的条形码来总计毛重。
此处的输出应为(0.418 + 0.568),因为它的条形码分别为247和248的最小日期。
答案 0 :(得分:3)
使用窗口函数为每个分区(ID)分配重新开始的行号 然后只需要rownumber 1和CTE或子查询,因为RN无法限制。
分区只是指定列中的一组记录。所以ID为247和248是不同的组,第1行将分配给每个分区中的最早日期。然后,当我们说rn = 1时,我们只得到每个不同ID的最早日期的权重!
WITH CTE AS (SELECT A.*
, Row_NUMBER() Over (Partition by ID order by Date asc) RN
FROM TABLE A)
SELECT Sum(Weight)
FROM CTE
WHERE RN = 1
答案 1 :(得分:1)
我相信一个简单的子查询就足够了
SELECT sum(weight)
FROM Table t1
WHERE DATE = (select min(DATE) from Table t2 where t1.ID = t2.ID group by id)
答案 2 :(得分:0)
;With cte([DATE],ID,[weight])
AS
(
SELECT '2017-04-25 11:05:42.273', 247, 0.418 Union all
SELECT '2017-04-25 11:05:42.310', 248, 0.568 Union all
SELECT '2017-04-25 13:57:55.327', 247, 0.418 Union all
SELECT '2017-04-25 13:57:55.360', 247, 0.534 Union all
SELECT '2017-04-25 13:57:55.397', 248, 0.568 Union all
SELECT '2017-04-25 13:57:55.453', 248, 0.448
)
SELECT Sum(MinWeight) [SumOFweight] From
(
SELECT ID,DATE,Min([weight])OVER(Partition by DATE) AS MinWeight ,Row_NUMBER() Over (Partition by ID order by Date asc) RN From
(
SELECT DATE,ID,SUM([weight])[weight] FROM cte
GROUP by ID,DATE
)dt
)Final
where Final.RN=1
输出
SumOFweight
-------------
0.986