我原来的表:
| Month | Nationality |
|----------|-------------|
| Oct 2015 | US |
| Oct 2015 | US |
| Oct 2015 | IT |
| Oct 2015 | CH |
| Nov 2015 | CH |
| Nov 2015 | CH |
| Nov 2015 | CH |
| Nov 2015 | BR |
| Nov 2015 | US |
我需要这个结果:
| Month | Nationality | Total |
|----------|-------------|-------|
| Oct 2015 | US | 2 |
| Oct 2015 | IT | 1 |
| Oct 2015 | CH | 1 |
| Nov 2015 | CH | 3 |
| Nov 2015 | BR | 1 |
| Nov 2015 | US | 1 |
我尝试了这个查询:
SELECT DISTINCT
P.[MONTH]
, COUNT(1) OVER ( PARTITION BY P.[Nationality] ) AS [Nationality]
FROM #PAXS P
但没有成功,我不知道如何保留列标题。
答案 0 :(得分:0)
GROUP BY
您不想汇总的字段:
SELECT P.[MONTH]
,P.[Nationality]
, COUNT(*) AS Total
FROM #PAXS P
GROUP BY P.[MONTH]
, P.[Nationality]
使用OVER(PARTITION BY..)
可以在组级别获取聚合,而无需对记录进行分组,在许多情况下都很有用。