问题描述
表格:
查询:
SELECT cintitule,cperiode,SUM(nmontant) FROM tsal_mois
WHERE cperiode between "201901" AND "201912"
GROUP BY cperiode,cintitule
结果:
问题:
我想按“ cperiode”列分组。
例如:我想要的结果
"date"
ccodrub cintitule all-cperiode sum_nmontant
001 Salaire de Base 2019 (I want all
001 Salaire de Base 2018 sum of all in 2019)
(I want all
the years
grouped by)
" the dates are by months
I want it by year"
SELECT ccodrub,cintitule,SUM(nmontant) FROM tsal_mois WHERE cperiode between "201901" AND "201912" GROUP BY cintitule,ccodrub
谢谢
解决方法
您可以使用字符串(或数学)函数提取年份。假设cperiode
是一个字符串:
SELECT cintitule,LEFT(cperiode,4) as year,SUM(nmontant)
FROM tsal_mois
WHERE cperiode between '201901"'AND '201912'
GROUP BY cintitule,4);
对于不使用适当功能的数据库,大多数数据库支持LEFT()
。
如果cperiod
实际上是一个数字,请改用FLOOR(cperiod/100)
。
我找到了我想要的东西,这个查询解决了我的问题,谢谢大家
DECLARE @tbl TABLE(Id INT,[Reported Date] DateTime,Device_ID INT)
INSERT INTO @tbl
VALUES
(1,'2016-03-09 09:08:32.827',1),(2,'2016-03-08 09:08:32.827',(3,(4,'2016-03-10 09:08:32.827',2),(5,'2016-03-05 09:08:32.827',2)
SELECT r.*
FROM ( SELECT DISTINCT Device_ID FROM @tbl ) d
CROSS APPLY ( SELECT TOP 1 *
FROM @tbl t
WHERE d.Device_ID = t.Device_ID ) r