我有一张这样的表
我正在尝试实现这样的表格:
这是我的询问。
select name,token , sum(qty) [Qty],sum(amount)from #temp
group by token,name
试着这样..
SELECT *
FROM (SELECT name,
qty,amt,
Token
FROM #temp1
) AS D
PIVOT(Sum(amt)
FOR Token IN ([10],[20],[100],[40],[5])) AS P
但它不起作用。
任何帮助将不胜感激。
答案 0 :(得分:2)
我认为你可以通过以下声明来实现它:
SELECT
[Name],
SUM((CASE WHEN [Token] = 10 THEN [QTY] ELSE 0 END)) AS Token_10_QTY,
SUM((CASE WHEN [Token] = 10 THEN [amt] ELSE 0 END)) AS Token_10_amt,
SUM((CASE WHEN [Token] = 50 THEN [QTY] ELSE 0 END)) AS Token_50_QTY,
SUM((CASE WHEN [Token] = 50 THEN [amt] ELSE 0 END)) AS Token_50_amt,
SUM((CASE WHEN [Token] = 100 THEN [QTY] ELSE 0 END)) AS Token_100_QTY,
SUM((CASE WHEN [Token] = 100 THEN [amt] ELSE 0 END)) AS Token_100_amt
FROM
#temp1
GROUP BY
[Name]
假设您的列QTY
和amt
为NOT NULL
。
我希望它会对你有所帮助。