开发者

Join 1 to Many from the same table and append to row

开发者 https://www.devze.com 2023-02-04 11:11 出处:网络
SQL Server 2005 1 Table ID Project_id ------------- 11 12 12 13 2 queries 1st query gets unique results based on the ID

SQL Server 2005

1 Table

ID Project_id   
-------------
1  1           
1  2           
1  2           
1  3

2 queries

1st query gets unique results based on the ID

ID 
---
1
2
3
4
5

2nd Query totals the number of project_id's by I开发者_运维知识库D

ID Project_id total
--------------------
1  1          1
1  2          2
1  3          1

I'm trying to combine the queries so that the results are in one row like this

ID Project_id _1 Project_id_2 Project_id_3
-------------------------------------------
1  1             2            1

Is this possible?


Well, I'm afraid you are gonna have to use dynamic sql, so be sure to visit this link before. Once you did that, you can try this:

DECLARE @Project VARCHAR(MAX), @Query VARCHAR(MAX)

SELECT @Project = COALESCE(@Project + ',', '') + QUOTENAME('Project_Id_' + CAST(Project_id AS VARCHAR))
FROM Project
GROUP BY Project_id

SET @Query = '
SELECT Id, '+@Project+'
FROM (SELECT Id, ''Project_Id_'' + CAST(Project_id AS VARCHAR) Project_Id, 1 AS Num FROM Project) P
PIVOT(SUM(Num) FOR Project_Id IN ('+@Project+')) PV'

EXEC(@Query)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号