我不认为自己是一个完整的SQL新手,但我现在已经盯着这个问题两天了,打开和关闭,我开始想起我可能!
使用以下两个表:
ID Category
1 Animal
2 Color
3 Sport
Name ID Value
Fred 1 Cat
Fred 2 Blue
Fred 3 Football
Sally 1 Dog
Sally 3 Jogging
James 2 Green
Anne 3 Swimming
我无法找到group by,sub-query,union,cte或pivot命令的任意组合,这些命令将从'(ID = 1或ID = 2)'查询返回的多行合并为不同的行有多列。
E.G:
where (ID=1 or ID=2)
Name Animal Color
Fred Cat Blue
Sally Dog NULL
James NULL Green
任何人都可以告诉我是否有一个有效的SQL解决方案,或者我是否在报告中应该由代码处理的事情上浪费时间?
由于
答案 0 :(得分:4)
这是PIVOT语法
SELECT Name,[1] as Animal, [2] as Color
FROM
(SELECT Name,Id,Value
FROM Table) AS SourceTable
PIVOT
(
MIN(Value)
FOR Id IN ([1], [2])
) AS PivotTable;
答案 1 :(得分:2)
你可以用:
Select a.Name as Name, a.Value as Animal, c.Value as Color
FROM
(SELECT Name, Value
FROM table2 INNER JOIN table1
ON table2.ID = table1.ID AND table2.ID =1) as a
LEFT JOIN
(SELECT Name, Value
FROM table2 INNER JOIN table1
ON table2.ID = table1.ID AND table2.ID =2) as c
ON a.Name = c.Name
UNION
Select c.Name as Name, a.Value as Animal, c.Value as Color
FROM
(SELECT Name, Value
FROM table2 INNER JOIN table1
ON table2.ID = table1.ID AND table2.ID =1) as a
RIGHT JOIN
(SELECT Name, Value
FROM table2 INNER JOIN table1
ON table2.ID = table1.ID AND table2.ID =2) as c
ON a.Name = c.Name
表2很奇怪,设计不是很好。
答案 2 :(得分:1)
WITH filtered_table AS (
SELECT Name, ID, Value
FROM table2
WHERE ID IN (1, 2)
)
SELECT
t2.Name,
Animal = MAX(CASE t1.ID WHEN 1 THEN ft.Value END),
Color = MAX(CASE t1.ID WHEN 2 THEN ft.Value END)
FROM (SELECT DISTINCT Name FROM filtered_table) t2
INNER JOIN table1 t1 ON t1.ID IN (1, 2)
LEFT JOIN filtered_table ft ON t2.Name = ft.Name AND t1.ID = ft.ID
GROUP BY t2.Name