sql 服务器 2008 select 行数语句
sql server 2008 select statement for rows count
我有两个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
我想要这样的结果
id pa_name breakfast lunch dinner day_des
1 A 2 1 2 des1
2 B 2 2 1 des11
我正在使用 SQL Server 2008
将 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?我的选择是最小值。
这将为您提供逗号分隔格式的值
;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
我有两个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
我想要这样的结果
id pa_name breakfast lunch dinner day_des
1 A 2 1 2 des1
2 B 2 2 1 des11
我正在使用 SQL Server 2008
将 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?我的选择是最小值。
这将为您提供逗号分隔格式的值
;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