我的表格数据如下:
UserData
表:
|ID| Name | TeamName |
| 1| Peter | Alpha |
| 1| Peter | Beta |
| 1| Peter | Gamma |
| 2| Mary | Gamma |
| 2| Mary | Omega |
| 3| John | Kappa |
| 3| John | Delta |
Name和TeamName的组合始终是唯一的。我需要每个唯一的ID和名称获得前1个TeamName和团队关系的数量,如下所示:
table #FinalTable
|ID| Name | TeamName | NumberOfRelations |
| 1| Peter | Alpha | 3 |
| 2| Mary | Gamma | 2 |
| 3| John | Kappa | 2 |
问题 - 有没有办法在一个查询中执行此操作,或者我是否必须使用临时表来选择前1个团队并计算关系数量,然后选择数据indo单独的最终表? 我试过这样的事情:
;WITH cte AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY TeamName Asc) AS rn
FROM UserData
)
SELECT * into #tempTable1
FROM cte
WHERE rn = 1
和此:
insert into #tempTable2 (ID, Name, NumberOfRelations)
select ID, Name, count(*) as NumberOfRelations
from UserData
group by ID, Name
...然后从两个临时表中选择数据。 我想知道是否有更简单的方法。
答案 0 :(得分:2)
对于SQLserver:
你没有订购,所以我在下面选择一个......
select top 1 with ties id,playen,count(id) over (partition by id,playen) as countt
,temaname
from #temp t1
order by row_number() over (partition by id,playen order by id,playen,temaname)
<强>输出:强>
id playen countt temaname
1 Peter 3 Alpha
2 Mary 2 Gamma
3 John 2 Delta
答案 1 :(得分:1)
假设这是SQL Server,请尝试:
Select t.ID, t.Name, team.TeamName, count(t.TeamName) countt
from @temp t join
(Select id, TeamName, Row_Number() over (Partition By ID Order By TeamName asc) as rn
from @temp) team on (team.ID = t.ID and team.rn=1)
Group by t.ID, t.Name, team.TeamName
答案 2 :(得分:0)
SQL表代表无序集。除非列指定排序,否则没有第一个团队名称。你似乎没有这样的专栏。
如果您有这样的专栏:
WITH cte AS (
SELECT ud.*,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ??) as seqnum,
COUNT(*) OVER (PARTITION BY ID) as cnt
FROM UserData ud
)
SELECT cte.*
FROM cte
WHERE seqnum = 1;
请注意??
。这是指定获取团队名称的顺序。根据数据库的不同,您可以使用NULL
或(SELECT NULL)
获取任意团队名称。