通过给我一个不同的总数来分组

时间:2018-03-15 13:15:24

标签: sql group-by

我正在进行sql查询,在那里我检索特定年份的帐户列表。我认为下面的代码很好。

    SELECT count(DISTINCT ACCOUNT) AS ACCOUNT,
       CASE when MONTH(Created)=1 then 'January' 
        when MONTH(Created)=2 then 'February'
        when MONTH(Created)=3 then 'March'
        when MONTH(Created)=4 then 'April'
        when MONTH(Created)=5 then 'May'
        when MONTH(Created)=6 then 'June'
        when MONTH(Created)=7 then 'July'
        when MONTH(Created)=8 then 'August'
        when MONTH(Created)=9 then 'September'
        when MONTH(Created)=10 then 'October'
        when MONTH(Created)=11 then 'November'
        when MONTH(Created)=12 then 'December'
        else '3' end AS MONTH
   FROM DB_Table
   WHERE
    AND (DB_Table.Cancelled < '1901-01-01' OR DB_Table Cancelled > '2017-12-31')    
    AND YEAR(Created)='2017'
   GROUP BY MONTH(Created)
   Order BY MONTH(Created)

直到我这样检查:

    Select count(DISTINCT ACCOUNT) AS ACCOUNT
    FROM DB_Table
    WHERE
    AND (DB_Table.Cancelled < '1901-01-01' OR DB_Table Cancelled > '2017-12-31')    
    AND YEAR(Created)='2017'

我有两个不同的总和,但似乎Group by给我的数量高于底部查询。 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

查询看起来很好,原因可能是您在不同月份拥有相同的数据,例如,1月份有一个帐户,9月份有3个帐户。查询全局时,它只计算一个。顺便说一句,我强烈建议使用MONTHNAME(mysql)或其他函数来加快查询速度。

Convert Month Number to Month Name Function in SQL

答案 1 :(得分:0)

只是在黑暗中捅了一下,因为你还没有清楚你输入/想要的​​输出,但我的猜测是,你可能只是想尝试这样做(DATENAME是SQL Server,FYI ):

SELECT COUNT(ACCOUNT) AS ACCOUNTs,
   DATENAME(month, Created) AS FullMonthName
FROM DB_Table
WHERE (DB_Table.Cancelled < '1901-01-01' OR DB_Table Cancelled > '2017-12-31')    
AND YEAR(Created)='2017'
GROUP BY DATENAME(month, Created)