-4

你能帮我用一个 sql 语句来按月和按年查找 Appid 计数顺序,但不要计算现有的月和年 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

4

2 回答 2

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]
于 2013-06-19T20:03:34.030 回答
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列存储?
于 2013-06-19T19:58:29.870 回答