I have two table
Table_1:
id pa_name
1 A
2 B
3 C
Table_2:
id breakfast lunch dinner day day_des
1 Yes Yes No 1 des1
1 No No Yes 2 des2
1 Yes No Yes 3 des3
2 Yes Yes Yes 1 des11
2 Yes No No 2 des22
2 No Yes No 3 des33
I want the result like that
id pa_name breakfast lunch dinner day_des
1 A 2 1 2 des1
2 B 2 2 1 des11
I am using SQL Server 2008
This will give you the values in Comma seperated format
;WITH CTE AS
(
SELECT t1.id, t1.pa_name,
SUM(CASE WHEN breakfast = 'YES' then 1 end) as breakfast,
SUM(CASE WHEN lunch = 'YES' THEN 1 END) AS lunch,
SUM(CASE WHEN dinner= 'YES' THEN 1 END) AS dinner
FROM Table_1 AS t1
JOIN Table_2 AS t2 ON t1.id = t2.id
GROUP BY t1.id, t1.pa_name
)
SELECT *,
SUBSTRING(
(SELECT ', ' + day_des
FROM TABLE_2 T2
WHERE CTE.id=id
FOR XML PATH('')),2,200000) day_des
FROM CTE
Combine a JOIN with GROUP BY:
select t1.id, t1.pa_name,
SUM(case when breakfast = 'YES' then 1 end) as breakfast,
SUM(case when lunch = 'YES' then 1 end) as lunch,
SUM(case when dinner= 'YES' then 1 end) as dinner,
MIN(day_des)
from Table_1 as t1 join Table_2 as t2 on t1.id = t2.id
group by t1.id, t1.pa_name
But I'm a bit concerned about the recent edit, how is day_des supposed to be picked if there are different values? My choice was MIN value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.