我有这张桌子
CUSTOMERNAME | PRODUCTNAME | AMMOUNT
=======================================
Customer1 Product1 10
Customer1 Product1 100
Customer2 Product2 20
Customer2 Product2 200
Customer1 Product2 30
Customer1 Product2 300
Customer2 Product1 40
Customer2 Product1 400
我需要这张桌子:
Product1 | Product2 .|.. ProductN
=================================
Sum(ammount) Sum(Ammount) | Sum(Ammount)
我明白我需要使用PIVOT。
这是我的尝试
Selectt temp.Product1, temp.Product2
FROM
(
select ProductName, Ammount
from CustomerProducts
)
PIVOT(
SUM(Ammount)
FOR ProductName IN (['Product1'])
) as temp
这是我的例外
Incorrect syntax near '.'.: Selectt temp.Product1, temp.Product2 FROM ( select ProductName, Ammount from CustomerProducts ) PIVOT( SUM(Ammount) FOR ProductName IN (['Product1']) ) as temp
答案 0 :(得分:2)
删除单引号,并包括您想要转动的所有产品,应该只是FOR ProductName IN([Product1],[Product2]),您还需要为子查询添加别名。您还在selectt
中添加了两个ts。
进行最终查询:
SELECT temp.Product1, temp.Product2
FROM ( SELECT ProductName, Ammount
FROM CustomerProducts
) AS c -- SUBQUERY ALIAS HERE
PIVOT
( SUM(Ammount)
FOR ProductName IN ([Product1], [Product2]) -- REMOVE SINGLE QUOTES, INCLUDE ALL PRODUCTS
) AS temp;
<强> Example on SQL Fiddle 强>