我正在尝试将行转置为列。 每个供应商一排,每年的毛利率为列。
这是给出的表:
SELECT
SupplierName,
CASE WHEN YearID = 2018 THEN Shipping_cost ELSE NULL END SC_2018,
CASE WHEN YearID = 2017 THEN Shipping_cost ELSE NULL END SC_2017,
CASE WHEN YearID = 2016 THEN Shipping_cost ELSE NULL END SC_2016,
CASE WHEN YearID = 2018 THEN Retail_Percent_2018 ELSE NULL END Retail_2018,
CASE WHEN YearID = 2017 THEN Retail_Percent_2017 ELSE NULL END Retail_2017,
CASE WHEN YearID = 2016 THEN Retail_Percent_2016 ELSE NULL END Retail_2016
FROM
(
SELECT
SUPL.SUP_NAM AS SupplierName,
SUPL.SUPL_CST AS Shipping_cost,
(SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
WHERE YearID = '2018') AS GRANDTOTAL_2018,
(SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
WHERE YearID = '2017') AS GRANDTOTAL_2017,
(SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
WHERE YearID = '2016') AS GRANDTOTAL_2016,
SUM(SUPL.Retail_Cost) AS Retail_Total,
CASE WHEN YearID = 2018
THEN (Retail_Total/GRANDTOTAL_2018) * 100
ELSE NULL END AS Retail_Percent_2018,
CASE WHEN YearID = 2017
THEN (Retail_Total/GRANDTOTAL_2017) * 100
ELSE NULL END AS Retail_Percent_2017,
CASE WHEN YearID = 2016
THEN (Retail_Total/GRANDTOTAL_2016) * 100
ELSE NULL END AS Retail_Percent_2016,
FROM MM_TRX_TABLE S
WHERE YEARID IN ('2018', '2017', '2016')
GROUP BY
SupplierName,
YEARID,
)DTL
ORDER BY GrossMargin DESC
我期待桌子看起来像:
但我让供应商重复多行。enter image description here
答案 0 :(得分:0)
我会试一试。
首先:你加入我的口味太多了。请记住,更少的连接通常意味着优化器的决策更少,因此代码更强大。此外,它通常首先表现更好。
如果您忽略了您希望零售以每年百分比表示的事实,那么解决起来非常简单:
Select
SupplierName,
Sum(CASE WHEN YearID = 2018 THEN Supl_cst ELSE NULL END) SC_2018,
Sum(CASE WHEN YearID = 2017 THEN Supl_cst ELSE NULL END) SC_2017,
Sum(CASE WHEN YearID = 2016 THEN Supl_cst ELSE NULL END) SC_2016,
Sum(CASE WHEN YearID = 2018 THEN Retail_cst ELSE NULL END) Retail_2018,
Sum(CASE WHEN YearID = 2017 THEN Retail_cst ELSE NULL END) Retail_2017,
Sum(CASE WHEN YearID = 2016 THEN Retail_cst ELSE NULL END) Retail_2016
FROM MM_TRX_TABLE S
WHERE YEARID IN (2018,2017,2016)
GROUP BY SupplierName
如果你想要百分比,只需将总数加回第一个结果并在总和中进行除法:
Select
SupplierName,
Sum(CASE WHEN YearID = 2018 THEN Supl_cst ELSE NULL END) SC_2018,
Sum(CASE WHEN YearID = 2017 THEN Supl_cst ELSE NULL END) SC_2017,
Sum(CASE WHEN YearID = 2016 THEN Supl_cst ELSE NULL END) SC_2016,
Sum(CASE WHEN YearID = 2018 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2018,
Sum(CASE WHEN YearID = 2017 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2017,
Sum(CASE WHEN YearID = 2016 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2016
FROM MM_TRX_TABLE S
Join (select
YearID,
sum(Retail_cst) Retail_total
Group by YearID
) T
Using (YearID)
WHERE S.YEARID IN (2018,2017,2016)
GROUP BY SupplierName