开发者

Query to merge multiple rows into into distinct rows with multiple columns

I don't consider myself a complete SQL novice, but I have been staring at this problem for two days now, on and off, and I am beginning to think maybe I am!

Using the following two tables:

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

I have been unable to find开发者_开发问答 any combination of group by, sub-query, union, cte or pivot commands that will merge the multiple rows returned from an ‘(ID = 1 or ID = 2)’ query into a distinct rows with multiple columns.

E.G.:

where (ID=1 or ID=2)

Name     Animal    Color
Fred     Cat       Blue
Sally    Dog       NULL
James    NULL      Green

Can anyone please advise me if there is an efficient SQL solution to this or am I wasting my time on something that should be handled by code in the report?

Thanks


Here goes the PIVOT syntax

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;


You can do it with:

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

The table 2 is strange and it's not very well designed.


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜