SQL计数和按日期和类型分组

时间:2015-09-28 09:36:50

标签: sql sql-server sql-server-2008 date

我有一张质量系统表。有两种类型的质量点NCR和RMA。 RMA是外部的,NCR是内部的。我们将交易记录到表中作为NCR或RMA。我希望有一个查询将计算所有RMA和所有NCR然后按月计数。例如:

      MONTH          RMA          NCR
      JANUARY        10           54
      FEBRUARY       48           22
      MARCH          25           55

如果该月的值为零或月份尚未出现,我不希望在报告中看到它。 桌子。这就是我所拥有的。

SELECT MONTH(QualityControl.CreateDate) MONTH, COUNT(*) AS 'NCR'
FROM QualityControl
WHERE YEAR(QualityControl.CreateDate)=2015
and
QualityControl.NCR is not null 
GROUP BY MONTH(QualityControl.CreateDate)

这只给出了月份编号(1 = 1月)和该月的NCR计数。

然后我尝试了以下内容:

SELECT 
  SUM(CASE datepart(month,CreateDate) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,CreateDate) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,CreateDate) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,CreateDate) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,CreateDate) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,CreateDate) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,CreateDate) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,CreateDate) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,CreateDate) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,CreateDate) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,CreateDate) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,CreateDate) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,CreateDate) WHEN 2015 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    QualityControl
WHERE
  CreateDate BETWEEN '2015/01/01' AND '2015/12/30'

它给了我NCR和RMA的计数

2 个答案:

答案 0 :(得分:0)

在sql server中你可以做所有这些:

SELECT 
CASE datepart(month,getdate()) WHEN 1 THEN 1 ELSE 0 END AS January,
CASE datepart(month,getdate()) WHEN 2 THEN 1 ELSE 0 END AS "February",
CASE datepart(month,getdate()) WHEN 3 THEN 1 ELSE 0 END AS [March]

最好的方法是     SELECT datename(month,getdate())

答案 1 :(得分:0)

让我们第一次尝试,每个值一行。您想要计算有效的“NCR”和“RMA”值。你可以使用这样的COUNT()

SELECT MONTH(qc.CreateDate) as MON, COUNT(NCR) as NCR, COUNT(RMA) as RMA
FROM QualityControl qc
WHERE CreateDate >= '2015-01-01' AND CreateDate < '2016-01-01' 
GROUP BY MONTH(qc.CreateDate)
ORDER BY MON;

使用列(或其他表达式),COUNT()计算非NULL值的数量。这似乎正是你想要的。

如果您想要SUM()的值,则可以使用SUM()代替COUNT()

注意日期:

  • 使用比较的版本优于使用YEAR()的版本,因为它可以使用索引。
  • 我将BETWEEN更改为>=<。如果您的日期/时间列具有时间组件,则此版本可以正常工作。它也适用于日期。
  • 12月有31天。