简单的SQL查询,可将多个属性展平在一行中

简单的SQL查询,可将多个属性展平在一行中,sql,postgresql,case,pgadmin,flatten,Sql,Postgresql,Case,Pgadmin,Flatten,我第一次尝试在Excel中解决我的问题,但没有简单的解决方法,所以决定尝试使用SQL(在PostgreSQL/pgAdminIII上),因为我是一个初学者,并且没有找到令人满意的解决方案 我的目标是“展平”一个数据集,该数据集在一行中包含相似的属性,并且应该有自己的一行 举个例子可以说明这一点。我的数据列出购物袋及其内容如下: id material color fruit1 fruit2 fruit3 1 cotton red apple banana cherry 2 pap

我第一次尝试在Excel中解决我的问题,但没有简单的解决方法,所以决定尝试使用SQL(在PostgreSQL/pgAdminIII上),因为我是一个初学者,并且没有找到令人满意的解决方案

我的目标是“展平”一个数据集,该数据集在一行中包含相似的属性,并且应该有自己的一行

举个例子可以说明这一点。我的数据列出购物袋及其内容如下:

id material color fruit1 fruit2 fruit3 
1  cotton   red   apple  banana cherry
2  paper    blue  apple  cherry
3  plastic  red   banana
我需要为每个水果创建一个包含新行的表,因此查询结果应该如下所示:

id material color fruit  
1  cotton   red   apple  
1  cotton   red   banana 
1  cotton   red   cherry
2  paper    blue  apple
2  paper    blue  cherry
3  plastic  red   banana
到目前为止,我提出了一个涉及CASE的查询,但这只返回第一个匹配项,因此没有返回所有需要的行

SELECT  
  id,
    (CASE 
        WHEN 'apple' IN(fruit1, fruit2, fruit3) THEN 'apple_exh'        
        WHEN 'banana' IN(fruit1, fruit2, fruit3) THEN 'banana_exh'
        WHEN 'cherry' IN(fruit1, fruit2, fruit3) THEN 'cherry_exh'              
        ELSE 'Error'
    END) as "Fruit_Here"
FROM 
  mydb.shopping
WHERE 
 'apple' IN(fruit1, fruit2, fruit3)
 OR
 'banana' IN(fruit1, fruit2, fruit3)
 OR
 'cherry' IN(fruit1, fruit2, fruit3)

ORDER BY id;
返回

id; fruit_here
1;"apple_exh"
2;"apple_exh"
3;"banana_exh"
id; fruit_here
1;"apple_exh"
1;"banana_exh"
1;"cherry_exh"
2;"apple_exh"
2;"cherry_exh"
3;"banana_exh"
如果有一个技巧允许CASE返回所有匹配项,而不仅仅是第一个匹配项,那就太好了。我目前的解决方法是使用一系列的CASEUNION ALL(参见下面的苹果和香蕉示例)来解决问题,但这并不现实,因为我的完整数据包括大约30种水果(可能我应该对蔬菜应用相同的“压扁”,最初也是在一行上)

返回

id; fruit_here
1;"apple_exh"
2;"apple_exh"
3;"banana_exh"
id; fruit_here
1;"apple_exh"
1;"banana_exh"
1;"cherry_exh"
2;"apple_exh"
2;"cherry_exh"
3;"banana_exh"

我的问题:有没有其他明显的方法可以在SQL中执行此任务,而不必为每种类型的水果重复代码

您只需要为每列使用select语句:

select id, material, color, fruit1 from mydb.shopping where fruit1 is not null
union 
select id, material, color, fruit2 from mydb.shopping where fruit2 is not null
union 
select id, material, color, fruit3 from mydb.shopping where fruit3 is not null

我使用sql进行报告,但找不到我的代码。 但以下是我在快速搜索中发现的内容。

非常感谢您阅读我的问题并发布此信息!这确实是我一直在寻找的简单解决方案。如果知道单独的select语句实际上在同一列中排列,那么无论源列名如何,结果都会在语句中按位置排列,这会有很大的帮助。因此,所有的水果最后都排成一列,标为“水果1”,这正是我所需要的。