sql查询月度数据

时间:2013-07-09 05:56:13

标签: sql sql-server

我写了这个查询,当我从下拉列表中选择一年时,它会提供所有12个月中所有365天的日数据。

SELECT
      YEAR(Date) AS [Year]
    , MONTH(Date) AS [Month]
    , COUNT(*) AS [Total]
FROM EnquiryMaster
WHERE EnquiryOwner = '" + enqowner + "'
     AND DATEPART(yyyy, Date) = '" + year + "'
     AND orgid = '" + orgid + "'
GROUP BY
      YEAR(Date)
    , MONTH(Date)

UNION ALL

SELECT
      YEAR(Date) AS [Year]
    , NULL
    , COUNT(*)
FROM EnquiryMaster
WHERE EnquiryOwner = '" + enqowner + "'
     AND DATEPART(yyyy, Date) = '" + year + "'
     AND orgid = '" + orgid + "'
GROUP BY YEAR(Date)

我想编写一个查询,它将选择月份以及年份,并仅显示该月的数据

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的,假设我理解了这个问题

SELECT
    DATEPART(yyyy, Date), 
    DATEPART(mm, Date),
    COUNT(*) AS [Total]
FROM EnquiryMaster
GROUP BY
    DATEPART(yyyy, Date), 
    DATEPART(mm, Date)
ORDER BY
    DATEPART(yyyy, Date), DATEPART(mm, Date)

答案 1 :(得分:0)

如果你只需要一个月的结果,那么把它放在where子句中(1表示jan,2表示feb)

SELECT
      YEAR(Date) AS [Year]
    , MONTH(Date) AS [Month]
    , COUNT(*) AS [Total]
FROM EnquiryMaster
WHERE EnquiryOwner = '" + enqowner + "'
     AND DATEPART(yyyy, Date) = '" + year + "'
     AND orgid = '" + orgid + "'
     AND MONTH(Date) = '" + month + "'
GROUP BY
      YEAR(Date)
    , MONTH(Date)

UNION ALL

SELECT
      YEAR(Date) AS [Year]
    , NULL
    , COUNT(*)
FROM EnquiryMaster
WHERE EnquiryOwner = '" + enqowner + "'
     AND DATEPART(yyyy, Date) = '" + year + "'
     AND orgid = '" + orgid + "'
      AND MONTH(Date) = '" + month + "'
GROUP BY YEAR(Date)