我们有3张桌子。
tid_color - 参数化表
--------------------------
ID ColorDescription
--------------------------
1 Green
2 Yellow
3 Red
-------------------------
tid_car - 参数化表
--------------------------
ID CARDescription
-------------------------
1 Car X
2 Car Y
3 Car Z
--------------------------
table_owners_cars
------------------------------------------------
ID CarID ColorID Owner
------------------------------------------------
1 1 1 John
2 1 2 Mary
3 1 3 Mary
4 1 3 Giovanni
5 2 2 Mary
6 3 1 Carl
7 1 1 Hawking
8 1 1 Fanny
------------------------------------------------
CarID是tid_car的外键
ColorId是tid_color的外键
如果我们编码:
SELECT tcar.CarDescription, tco.ColorDescription, Count(*) as Total
FROM table_owners_cars tocar
LEFT JOIN tid_color tco ON tco.Id = tocar.ColorId
LEFT JOIN tid_Car tcar ON tcar.Id = tocar.CarId
GROUP BY CarDescription, ColorDescription
结果为:
Id CarDescription ColorDescription Total
1 CarX Green 3
2 CarX Yellow 1
3 CarX Red 1
4 CarY Yellow 1
5 CarZ Green 1
但我想在HEADER中使用Color,所以我的代码为
SELECT CarId, [1] as 'Green', [2] as 'Yellow', [3] as 'Red', [1]+[2]+[3] as 'total'
FROM
(SELECT CarID, colorId
FROM table_owners_cars tocar
LEFT JOIN tid_car tc ON tocar.CarId=tc.Id) p
PIVOT
(
COUNT (ColorId)
FOR ColorId IN ( [1], [2], [3])
) AS pvt
带有此类SQL的结果表:
---------------------------------------------
Id Car Green Yellow Red Total
---------------------------------------------
1 1 3 1 1 5
2 2 0 1 0 1
3 3 1 0 0 1
---------------------------------------------
它不能将汽车的描述(CarX,CarY,CarZ)放在Car列中......而不是我之前试过的代码中的第一个选择
SELECT tc.CarDescription, [1] as 'Green', [2] as 'Yellow', [3] as 'Red', [1]+[2]+[3] as 'total'
然后抛出
无法绑定多部分标识符“tc.CarDescription”。
我希望拥有 CarDescription ,而不是最后一个表中显示的ID。我希望有的表格如下。
我想完全按照以下方式进行转移:
---------------------------------------------
Id Car Green Yellow Red Total
---------------------------------------------
1 CarX 3 1 1 5
2 CarY 0 1 0 1
3 CarZ 1 0 0 1
---------------------------------------------
如何实现这一目标?谢谢。
答案 0 :(得分:1)
您可以加入Pivoted结果:
SELECT pvt.CarID, tc.Description AS Car, [1] as 'Green', [2] as 'Yellow', [3] as 'Red', [1]+[2]+[3] as 'total'
FROM
(SELECT CarID, colorId
FROM table_owners_cars tocar
) p
PIVOT
(
COUNT (ColorId)
FOR ColorId IN ( [1], [2], [3])
) AS pvt
INNER JOIN tid_car tc ON pvt.CarId=tc.Id