SQL将1个字段,多个记录转换为1个记录多个字段

时间:2013-03-18 22:45:40

标签: sql ms-access self-join

如果我更有经验,我可以使用类似的"合并行"要弄明白的问题,但我不能让他们工作。我有大概2000"车库"在具有某些类别的accdb中(实际上是具有患者数据的诊所,但在此简化)。以下是一个车库数据存在的示例:

Garage ID   Car_Color        Sub_Type?   Color_Count
    42       Blue            Striped        5
    42       Blue                           10
    42       Red                            23
    42       Yellow                         2

我需要将每个车库变成一个单独的记录,每种颜色作为一个单独的字段,其中显示计数,所需的输出:

Garage ID   Blue Cars (total)  Blue Cars (striped)   Red Cars  Yellow Cars   Orange Cars
    42         15                    5                  23          2             0

有一个带有子类型的类别,此处显示为" Blue Cars"和"蓝色汽车(条纹)"。对于那些人,我需要总结一下" Blue"没有子类型与另一个"蓝"算得到总数"蓝"计数。然后我会将Blue子类型列为单独的字段。大多数车库没有列出橙色汽车,所以当没有橙色汽车记录时,我需要让该记录显示0,但如果有记录,则需要反映计数。

这似乎与其他自我联接非常相似,但我无法让计数方面发挥作用,或者' 0'没有记录。

2 个答案:

答案 0 :(得分:5)

您可以将聚合函数与IIF()表达式一起使用:

select [Garage ID],
  sum(IIF(Car_color='Blue', Color_Count, 0)) as BlueCarsTotal,
  sum(IIF(Car_color='Blue' AND [Sub_Type?]='Striped', Color_Count, 0)) as BlueCarsStripedTotal,
  sum(IIF(Car_color='Red', Color_Count, 0)) as RedCarsTotal,
  sum(IIF(Car_color='Yellow', Color_Count, 0)) as YellowCarsTotal,
  sum(IIF(Car_color='Orange', Color_Count, 0)) as OrangeCarsTotal
from yourtable
group by [Garage ID]

如果您在另一个允许CASE表达式的数据库中执行此操作,则查询将为:

select [Garage ID],
  sum(case 
       when Car_color='Blue' 
       then Color_Count else 0 end) as BlueCarsTotal
  sum(case 
       when Car_color='Blue' AND [Sub_Type?]='Striped' 
       then Color_Count else 0 end) as BlueCarsStripedTotal,
  sum(case 
       when Car_color='Red' 
       then Color_Count else 0 end) as RedCarsTotal,
  sum(case 
       when Car_color='Yellow' 
       then Color_Count else 0 end) as YellowCarsTotal,
  sum(case 
       when Car_color='Orange' 
       then Color_Count else 0 end) as OrangeCarsTotal
from yourtable
group by [Garage ID]

答案 1 :(得分:3)

交叉表可能适合:

TRANSFORM Sum(Garages.Color_Count) AS SumOfColor_Count
SELECT Garages.GarageID
FROM Garages
GROUP BY Garages.GarageID
PIVOT [Car_Color] & " " & [sub_type?];