即使计数为0,如何按周分组

时间:2019-04-26 12:26:57

标签: sql-server group-by left-join

我下面的示例很好用,我面临的唯一挑战是结果为0的几周没有显示。 这是我的代码示例:

SELECT 
DATENAME (WK, DATE) AS WEEK,
COUNT (DISTINCT COMPANY_ID) AS AMOUNT
FROM
(
SELECT COMPANY, DATE = MIN(DATE)
FROM TABLE1 A INNER JOIN TABLE2 B
ON A.ID = B.ID
WHERE YEAR(A.DATE) = '2019' AND COMPANY_ID NOT IN(SELECT COMPANY_ID  FROM 
TABLE1 A INNER JOIN TABLE2 B  ON A.ID = B.ID AND DATE < '2019-01-01') GROUP 
BY COMPANY_ID) d    

GROUP BY dateadd(wk, datediff(wk, 0, DATE), 0),  DATENAME(WK, DATE) 
ORDER BY dateadd(wk, datediff(wk, 0, DATE), 0)

我当前的输出如下:

week      | amount
4        |  354
6        |  222
7        |  144
8        |  354
9        |  45
10       |  55
11       |  76
12       |  98
13       |  45
14       |  344

以上结果缺少很多周(1、2、3和15、16、17等) 如何显示那些计数为0的数字?

我想要的输出:

week     | amount
1        |  0
2        |  0
3        |  0
4        |  354
6        |  222
7        |  144
8        |  354
9        |  45
10       |  55
11       |  76
12       |  98
13       |  45
14       |  344
15       |  0
16       |  0
17       |  0

2 个答案:

答案 0 :(得分:0)

需要注意的事情-

1)您当前的查询不正确(可能是您删除了其中的一部分以隐藏机密内容)。 例如在名为“ d”的子查询中,GROUP BY在“ company_id”列上,但是对“ company”进行了SELECT编辑。

SELECT  DATENAME (WK, DATE) AS WEEK,
    COUNT (DISTINCT COMPANY_ID) AS AMOUNT
FROM    
(
    SELECT COMPANY /*Different from group_by clause*/, DATE = MIN(DATE)
    FROM TABLE1 A INNER JOIN TABLE2 B ON (A.ID = B.ID)
    WHERE   YEAR(A.DATE) = '2019' 
        AND COMPANY_ID NOT IN 
        (   
            SELECT COMPANY_ID
            FROM TABLE1 A INNER JOIN TABLE2 B ON A.ID = B.ID AND DATE < '2019-01-01'
        ) 
    GROUP BY COMPANY_ID
) d    
GROUP BY dateadd(wk, datediff(wk, 0, DATE), 0),  DATENAME(WK, DATE) 
ORDER BY dateadd(wk, datediff(wk, 0, DATE), 0)

2)希望在编辑时不要误删除任何子句。

3)请您发布一些输入数据以更好地了解输出。

(在这里发表的道歉,因为我没有评论的权限。)

答案 1 :(得分:0)

首先创建一个包含所有星期数的临时表

然后与您的查询一起加入

DECLARE @Weeks AS Table(ID int)

DECLARE @i int = 1


WHILE @i < 53
BEGIN
INSERT INTO @Weeks (ID)
VALUES(@i)
SET @i = @i  + 1
END

SELECT * FROM @Weeks


SELECT 
DATENAME (WK, DATE) AS WEEK,
COUNT (DISTINCT COMPANY_ID) AS AMOUNT
FROM
(
SELECT COMPANY, DATE = MIN(DATE)
FROM TABLE1 A INNER JOIN TABLE2 B
ON A.ID = B.ID
RIGHT OUTER JOIN @Weeks W ON W.ID = DATENAME (WK, DATE) 
WHERE YEAR(A.DATE) = '2019' AND COMPANY_ID NOT IN(SELECT COMPANY_ID  FROM 
TABLE1 A INNER JOIN TABLE2 B  ON A.ID = B.ID AND DATE < '2019-01-01') GROUP 
BY COMPANY_ID) d    

GROUP BY dateadd(wk, datediff(wk, 0, DATE), 0),  DATENAME(WK, DATE) 
ORDER BY dateadd(wk, datediff(wk, 0, DATE), 0)