如何使用月份名称打印sql查询的结果

时间:2015-11-03 10:32:59

标签: sql-server-2008

我有一个SQL查询,用月检索计数。

前:

 January - 5
 February - 2 so on.

我需要知道的是,如果没有特定月份的记录,如何打印该月份并将其计数显示为0.

这是我的疑问:

select 
    DATETNAME(MONTH, c.postTime) as Month, COUNT(c.regNo) as Count
from 
    Company c
where
    DATENAME(YEAR, c.postTime) = 2015
group by 
    c.postTime

此查询返回以下结果:

MONTH   | Count
-----------------
July    | 2
August  | 1

我正在寻找的结果应该是:

MONTH   | Count
-----------------
January | 0
February| 0
March   | 0
April   | 0
May     | 0
June    | 0
July    | 2
August  | 1
.
.
.

so on...

2 个答案:

答案 0 :(得分:2)

一种方法是从锚点查询驱动它们,其中所有月份列表都是明确写入的,然后是left join您的表格company

SELECT m.Name, COUNT(COALESCE(c.regNo, 0)) as Count
FROM
(
   VALUES ('Janurary'), ('February'), ('March'),
          ('April'),    ('May'),      ('June'),
          ('July'),     ('August'),   ('September'),
          ('October'),  ('November'), ('December')
) AS m(Name)
LEFT JOIN Company c ON DATETNAME(MONTH, c.postTime) = m.Name
WHERE DATENAME(YEAR, c.postTime) = 2015
GROUP BY m.Name;

如果表格company没有任何特定月份,则会显示计数0。

您还可以使用递归CTE生成1到12之间的数字,并将这些整数转换为月份名称:

;WITH CTE 
AS
(
    SELECT 1 AS n
    UNION ALL
    SELECT n + 1
    FROM CTE
    WHERE n < 12
), Months
AS
(
    SELECT DATENAME(Month, 
                    DATEADD(Month, 
                            n-1, 
                            CAST('2015-01-01' AS datetime)))  AS Name
    FROM CTE
)
SELECT m.Name, COUNT(COALESCE(c.regNo, 0)) as Count
FROM Months AS m
LEFT JOIN Company c ON DATETNAME(MONTH, c.postTime) = m.Name
WHERE DATENAME(YEAR, c.postTime) = 2015
GROUP BY m.Name;

答案 1 :(得分:0)

 /**
  * A drawable that can draw a "Drawer hamburger" menu or an arrow and animate between them.
  * <p>
  * The progress between the two states is controlled via {@link #setProgress(float)}.
  * </p>
  */
 public class DrawerArrowDrawable extends Drawable{}

使用And而不是“Where”关键字。然后它按预期工作。