如何按月显示月份的计数

时间:2013-06-19 19:46:20

标签: sql-server-2008

你可以帮我用sql语句按月和明年查找Appid计数顺序,但不计算现有的Month&年appid

column name     TYPE   
ID          int 
AppID           int 
Month           int 
Year            int 

Records
ID Appid Month Year
207 396 Jan 2013
250 396 Feb 2013
283 396 Mar 2013
319 396 Apr 2013
365 396 May 2013
221 451 Feb 2013
262 451 Mar 2013
293 451 Apr 2013
329 451 May 2013
384 451 June 2013
354 609 May 2013
394 702 June 2013
353 707 May 2013

我想要输出如下,

Month      count
January     1
February    1
March       0
April       0
May         2
June        1

例如,如果appid = 396我想只显示所有appid的最小月份记录数,那么只有2月值是1

2 个答案:

答案 0 :(得分:3)

我相信您只想在第一个月计算每个Appid。所以,假设SQL Server 2005 +:

;WITH CTE AS
(
    SELECT  *,
            RN=ROW_NUMBER() OVER(PARTITION BY Appid ORDER BY ID)
    FROM YourTable
)

SELECT  A.[Year],
        A.[Month],
        COUNT(B.ID)
FROM (  SELECT DISTINCT [Year], [Month]
        FROM YourTable) A
LEFT JOIN ( SELECT *
            FROM CTE
            WHERE RN = 1) B
    ON A.[Year] = B.[Year] 
    AND A.[Month] = B.[Month]
GROUP BY A.[Year],
         A.[Month]

答案 1 :(得分:2)

根据您的样本记录,输出(在地球上)将如下所示:

| MONTH |   COUNT  |
--------------------
|   Apr |        2 |
|   Feb |        2 |
|   Jan |        1 |
|  June |        2 |
|   Mar |        2 |
|   May |        4 |

来自

SELECT Month, COUNT(*)
FROM gargle
GROUP BY Month

这引出了问题......

  1. 您使用什么逻辑来更改所需结果中的记录数?
  2. 您是否正在尝试填写特定 appid的缺失月份?
  3. 为什么要单独存储monthyear而不是date列?