计算一年中每个月的行数 - SQL Server

时间:2016-09-07 09:28:22

标签: sql sql-server sql-server-2008 stored-procedures

我有一个表“产品”:

| ProductId  | ProductCatId | Price  |      Date    |   Deadline   |
--------------------------------------------------------------------
|     1      |      1       |  10.00 |   2016-01-01 |  2016-01-27  |
|     2      |      2       |  10.00 |   2016-02-01 |  2016-02-27  |
|     3      |      3       |  10.00 |   2016-03-01 |  2016-03-27  |
|     4      |      1       |  10.00 |   2016-04-01 |  2016-04-27  |
|     5      |      3       |  10.00 |   2016-05-01 |  2016-05-27  |
|     6      |      3       |  10.00 |   2016-06-01 |  2016-06-27  |   
|     7      |      1       |  20.00 |   2016-01-01 |  2016-01-27  |
|     8      |      2       |  30.00 |   2016-02-01 |  2016-02-27  |
|     9      |      1       |  40.00 |   2016-03-01 |  2016-03-27  |
|     10     |      4       |  15.00 |   2016-04-01 |  2016-04-27  |
|     11     |      1       |  25.00 |   2016-05-01 |  2016-05-27  |
|     12     |      5       |  55.00 |   2016-06-01 |  2016-06-27  |
|     13     |      5       |  55.00 |   2016-06-01 |  2016-01-27  |
|     14     |      5       |  55.00 |   2016-06-01 |  2016-02-27  |
|     15     |      5       |  55.00 |   2016-06-01 |  2016-03-27  |

我想每个月创建产品的SP计数行,条件为Year = CurrentYear,如:

| Month| SumProducts | SumExpiredProducts |
-------------------------------------------
|   1  |      3      |         3          |
|   2  |      3      |         3          |
|   3  |      3      |         3          |
|   4  |      2      |         2          |
|   5  |      2      |         2          |
|   6  |      2      |         2          |

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以使用如下查询:

SELECT MONTH([Date]), 
       COUNT(*) AS SumProducts ,
       COUNT(CASE WHEN [Date] > Deadline THEN 1 END) AS SumExpiredProducts 
FROM mytable
WHERE YEAR([Date]) = YEAR(GETDATE())
GROUP BY MONTH([Date])