SQL Query打印没有记录的月份列表

时间:2014-05-16 15:05:36

标签: sql sql-server

我编写了一个查询来获取Northwind DB的ORDERS表中的所有记录,

select count(*) as COUN,month(OrderDate) as Mon
from orders 
where  Year(OrderDate) = '1996' 
group by month(OrderDate)

这里我要打印所有没有任何记录的月份。 任何建议都会有所帮助。

4 个答案:

答案 0 :(得分:0)

这应该有效:

select count(*) as COUN,month(OrderDate) as Mon
from orders 
where  Year(OrderDate) = '1996' 
AND NOT month(OrderDate) IN(SELECT month(OrderDate) from Orders WHERE Year(OrderDate) = '1996')
group by month(OrderDate)

答案 1 :(得分:0)

您可以使用WITH - 系列来生成您感兴趣的月份:

WITH mons AS
  (
    SELECT  1 AS num
    UNION ALL
    SELECT  num + 1
    FROM    mons
    WHERE   num < 12
  )
SELECT COUNT(*) AS COUNT, num
  FROM mons
  LEFT JOIN orders ON MONTH(OrderDate) = num
  WHERE YEAR(OrderDate) = '1996'
  GROUP BY num;

答案 2 :(得分:0)

您可以使用having子句来避免两次查询Orders表:

select count(*) as COUN,month(OrderDate) as Mon
from orders 
where  Year(OrderDate) = '1996' 
group by month(OrderDate)
having count(*) = 0

答案 3 :(得分:0)

根据this回答,您可以尝试以下方法:

--Example Setup
CREATE TABLE FORDERS (OrderDate datetime)

INSERT INTO FORDERS (OrderDate)
    VALUES (GETDATE());

--Actual Query.
DECLARE @Year varchar(4) = 1996;

DECLARE @StartDate  datetime = @Year + '0101',
        @EndDate    datetime = @Year + '1231';


SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName, COUNT(OrderDate)
FROM    master.dbo.spt_values x
    LEFT JOIN FOrders ON x.number = MONTH(OrderDate)
        AND YEAR(OrderDate) = @Year
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate)
GROUP BY x.number, MONTH(OrderDate)
HAVING COUNT(OrderDate) = 0;