我有两张桌子
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
我想要那样的结果
id pa_name breakfast lunch dinner day_des
1 A 2 1 2 des1
2 B 2 2 1 des11
我正在使用SQL Server 2008
答案 0 :(得分:1)
这将以逗号分隔格式
为您提供值;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
答案 1 :(得分:0)
将JOIN与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
但是我对最近的编辑有点担心,如果有不同的值,day_des应该如何被选中?我的选择是MIN值。