Sql server 使用累计和子查询后的前9条不同记录
我有以下数据结构的SQL数据表Sql server 使用累计和子查询后的前9条不同记录,sql-server,stored-procedures,gridview,Sql Server,Stored Procedures,Gridview,我有以下数据结构的SQL数据表 ID Hrly Hshed Dust_removal_to_done Dust_removal_done Update_datetime 2 ER MGS 4 4 2009-05-05 3 ER AQ 4 2 2009-05-05
ID Hrly Hshed Dust_removal_to_done Dust_removal_done Update_datetime
2 ER MGS 4 4 2009-05-05
3 ER AQ 4 2 2009-05-05
4 SR ANDA 4 4 2009-05-05
5 ECR HOME 5 5 2009-05-05
6 NR GZB 5 5 2009-05-05
7 NR LDH 5 5 2009-05-05
8 NCR JHS 5 5 2009-05-05
9 NCR CNB 5 5 2009-06-05
10 SCR LGD 5 5 2009-06-05
11 SCR LGD 5 5 2009-05-05
数据由用户每天提供
此外,我正在使用一个存储过程来计算“除尘完成”的累计总和,如下所示
ALTER PROCEDURE [dbo].[RAP_regular] as
SELECT Hshed, HRly, Dust_removal_to_done, Dust_removal_done, (SELECT SUM(Dust_removal_done) FROM TPHRAP_regular t2
where t2.Hshed = TPHRAP_regular.Hshed and t2.Update_datetime <= TPHRAP_regular.Update_datetime) as cumulative_dust_removal
FROM TPHRAP_regular
这很好用。现在的问题是只有9个Hshed,因此我希望在网格视图中仅显示9条最新记录(唯一的Hshed以及累积列)作为最终结果,以便表中不会重复Hshed。如何做到这一点?请帮忙 您需要更改存储过程(必须在其中,因为您要丢弃其中的日期字段) 您可以使用
ROW\u NUMBER()
window函数仅过滤最新记录,如下所示:
SELECT Hshed,HRly,Dust_removal_to_done,Dust_removal_done,cumulative_dust_removal
FROM(
SELECT Hshed, HRly, Dust_removal_to_done, Dust_removal_done,
(SELECT SUM(Dust_removal_done) FROM TPHRAP_regular t2
where t2.Hshed = TPHRAP_regular.Hshed
and t2.Update_datetime <= TPHRAP_regular.Update_datetime) as cumulative_dust_removal,
ROW_NUMBER() OVER (PARTITION BY Hshed ORDER BY Update_datetime DESC) as rnk
FROM TPHRAP_regular)
WHERE rnk = 1
您为什么不将总和与group by一起使用(没有子查询)?Thanx提供了有价值的帮助,但这给出了一个错误“关键字“WHERE”附近的语法不正确”。@user1185088更新了答案,也更改了您的相关查询。先生,因为我使用的是SQL server 2008,“并行数据仓库(PDW)”“功能未启用”,因此解决方案对我不起作用,即使它可能在SQL server 2012中工作。@user1185088
ROW_NUMBER()
适用于该版本,请使用我的第二个查询,但只需将SUM()OVER()
替换为相关查询即可。非常感谢先生。第一个解决方案是在TPHRAP_(常规)的后面插入't',对我有效。
SELECT Hshed,HRly,Dust_removal_to_done,Dust_removal_done,cumulative_dust_removal
FROM(
SELECT Hshed, HRly, Dust_removal_to_done, Dust_removal_done,
(SELECT SUM(Dust_removal_done) FROM TPHRAP_regular t2
where t2.Hshed = TPHRAP_regular.Hshed
and t2.Update_datetime <= TPHRAP_regular.Update_datetime) as cumulative_dust_removal,
ROW_NUMBER() OVER (PARTITION BY Hshed ORDER BY Update_datetime DESC) as rnk
FROM TPHRAP_regular)
WHERE rnk = 1
SELECT t.Hshed,
t.HRly,
t.Dust_removal_to_done,
t.Dust_removal_done,
t.cumulative_dust_removal
FROM (SELECT Hshed,
HRly,
Dust_removal_to_done,
Dust_removal_done,
SUM(Dust_removal_done) OVER(PARTITION BY Hshed ORDER BY Update_datetime) as cumulative_dust_removal,
ROW_NUMBER() OVER(PARTITION BY Hshed ORDER BY Update_datetime DESC) as rnk
FROM TPHRAP_regular) t
WHERE t.rnk = 1