当我们使用分组

时间:2016-04-08 10:23:39

标签: sql-server database relational-database aggregate-functions

我们应该如何重新发送这个查询,我没有找到解决方案来删除每个组的第二行...我需要帮助请...是否有一个函数或某些东西只能为组返回不同的值使用rolllup(此处不能使用)

SELECT 
    -- ROW_NUMBER() over (ORDER BY FF_DATE asc) as "numSituation"
     FF_NUMERO as "numFacture"
    , FF_DATE as "dateFacture"
    , FF_DATEREG as "dateReglement"
    , SUM(FF_D_HT) as "montantHT"
    , SUM(FF_D_TTC) as "montantTTC"
FROM F_FACTURESFOU
 INNER JOIN F_LIGNEFACFOU ON LFF_FFPTR = FF_NUMERO
 INNER JOIN F_LOT ON LFF_LT_IDENT = LT_IDENT
WHERE LFF_CODE_AFF = '14031-00' AND LT_CODE IN ('S83') AND FF_DATEVALID is not null
GROUP BY FF_NUMERO , FF_DATE, FF_DATEREG WITH ROLLUP 
HAVING ( ( FF_NUMERO is not null and FF_DATE IS NOT NULL ) OR ( FF_NUMERO is null and FF_DATE is null ))
ORDER BY GROUPING(FF_NUMERO ), FF_NUMERO, GROUPING ( FF_DATE), FF_DATE , GROUPING ( FF_DATEREG), FF_DATEREG

结果如下:

15E1500062  2015-07-24 00:00:00.000 NULL    3000.00 3600.00
15E1500062  2015-07-24 00:00:00.000 NULL    3000.00 3600.00  
15E1500063  2015-07-31 00:00:00.000 NULL    6000.00 7200.00
15E1500063  2015-07-31 00:00:00.000 NULL    6000.00 7200.00
15E1600423  2015-09-11 00:00:00.000 NULL    3000.00 3600.00
15E1600423  2015-09-11 00:00:00.000 NULL    3000.00 3600.00
NULL                      NULL      NULL    12000.00 14400.00

2 个答案:

答案 0 :(得分:0)

您可以将SQL Row_Number()函数与Partition By子句一起使用 您可以在Partition By子句

定义的每个组中的结果集中对行进行编号

然后,您可以排除row_number值大于或等于2

的所有行

请检查SQL Server中的SQL教程Row_Number() Over Partition By to delete duplicate rows

ROW_NUMBER() over (Partition By FF_NUMERO, FF_DATE ORDER BY

您可以按如下方式使用SQL CTE expression

;with cte as (
SELECT 
     ROW_NUMBER() over (Partition By FF_NUMERO, FF_DATE ORDER BY .... DESC) as rn,
    ....
FROM ....
)
SELECT * from cte where rn = 1

答案 1 :(得分:0)

感谢您的回答Eralper,我可以将row_number与keyr一起使用"使用" ...并且它可以工作(y)