答案 0 :(得分:0)
这是一种不依赖于专有PIVOT()
函数的数据库(包括SQL Server)的方法。在这样的例子中,这样做52周有点奇怪(但是,实际上,105个结果列并不是人类阅读报告的最佳输出)。
话虽如此,在这个例子中,我这样做的时间是一年而不是几周,而你只需要重复52次而不是4次。
实际上,您可以使用perl或Visual Basic或任何您喜欢的语句来生成语句。
这是:
-- the input table, don't use in real query ...
WITH
input(id,quarter,orders,cost) AS (
SELECT 1,201601,200,1000
UNION ALL SELECT 1,201602,300,1500
UNION ALL SELECT 1,201603,330,1800
UNION ALL SELECT 1,201604,500,2500
)
-- end of input -
SELECT
id
, SUM(CASE quarter WHEN 201601 THEN orders END) AS "orders_201601"
, SUM(CASE quarter WHEN 201602 THEN orders END) AS "orders_201602"
, SUM(CASE quarter WHEN 201603 THEN orders END) AS "orders_201603"
, SUM(CASE quarter WHEN 201604 THEN orders END) AS "orders_201604"
, SUM(CASE quarter WHEN 201601 THEN cost END) AS "cost_201601"
, SUM(CASE quarter WHEN 201602 THEN cost END) AS "cost_201602"
, SUM(CASE quarter WHEN 201603 THEN cost END) AS "cost_201603"
, SUM(CASE quarter WHEN 201604 THEN cost END) AS "cost_201604"
FROM input
GROUP BY id;
id|orders_201601|orders_201602|orders_201603|orders_201604|cost_201601|cost_201602|cost_201603|cost_201604
1| 200| 300| 330| 500| 1,000| 1,500| 1,800| 2,500