你可以帮我用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
答案 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
这引出了问题......
appid
的缺失月份?month
和year
而不是date
列?