如何按两个群组分组?

问题描述

表格:

enter image description here

查询

SELECT cintitule,cperiode,SUM(nmontant) FROM tsal_mois 
WHERE cperiode between "201901" AND "201912" 
GROUP BY cperiode,cintitule

结果:

enter image description here

问题:

我想按“ 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...