我需要我的sql查询返回:
Data_Type
一行(无论是否为该类型输入了数据)Date_Entered DESC
排序,然后按Data_ID DESC
排序)示例:
Data_Type_ID Data_Type
-------------------------------------
1 Height
2 Length
3 Weight
4 Width
Data_ID Data_Type_ID Data Date_Entered
-------------------------------------
1 4 4 4/6/2016
2 1 8 4/7/2016
3 3 7 4/4/2016
4 3 5 4/7/2016
5 4 1 4/5/2016
6 1 12 4/5/2016
7 4 3 4/6/2016
我想回来:
Data_Type Total Most_Recent
-------------------------------------
Height 20 8
Length 0 0
Weight 12 5
Width 8 3
现在,我有:
SELECT
t.Data_Type
, ISNULL(SUM(d.Data), 0) AS Total
--, ISNULL(??, 0) AS Most_Recent
FROM
Data_Type_Table t
LEFT JOIN
Data_Table d ON t.Data_Type_ID = d.Data_Type_ID
GROUP BY
t.Data_Type
这为每个Data_Type成功返回一行,其中包含该Data_Type的所有Data值的总和,如果不存在值,则为0。我不确定如何修改我的查询以为每个Data_Type添加最新的数据值。
答案 0 :(得分:2)
您可以使用窗口函数:ROW_NUMBER
和SUM OVER
:
WITH Cte AS(
SELECT
dtt.*,
dt.Data,
Total = SUM(dt.Data) OVER(PARTITION BY dtt.Data_Type_ID),
rn = ROW_NUMBER() OVER(PARTITION by dtt.Data_Type_ID ORDER BY dt.Date_Entered DESC)
FROM Data_Type_Table dtt
LEFT JOIN Data_Table dt
ON dt.Data_Type_ID = dtt.Data_Type_ID
)
SELECT
Data_Type,
Total = ISNULL(Total, 0),
Most_Recent = ISNULL(Data, 0)
FROM CTE
WHERE rn = 1
答案 1 :(得分:2)
我会使用条件聚合来解决这个问题:
SELECT t.Data_Type, COALESCE(SUM(d.Data), 0) AS Total,
MAX(CASE WHEN seqnum = 1 THEN d.data ELSE 0 END) as MostRecent
FROM Data_Type_Table t LEFT JOIN
(SELECT d.*,
ROW_NUMBER() OVER (PARTITION BY DataTypeId ORDER BY Date_Entered DESC) as seqnum
FROM Data_Table d
)
ON t.Data_Type_ID = d.Data_Type_ID
GROUP BY t.Data_Type;