[英]T-SQL: Rows to Columns
我是 SQL 初學者,所以有人可以幫我嗎?
我有一張這樣的桌子
YearMonth | Customer | Currency | BusinessType | Amount
04-2020 | 123 | EUR | Budget | 500
04-2020 | 123 | EUR | Forecast | 300
04-2020 | 123 | EUR | Sales | 700
現在我需要它:
YearMonth | Customer | Currency | Amount Budget | Amount Forecast | Amount Sales
04-2020 | 123 | EUR | 500 | 300 | 700
這樣的事情可能嗎? 在此先感謝您的幫助!
使用條件聚合:
select yearmonth, customer, currency,
sum(case when businesstype = 'Budget' then amount end) as budget,
sum(case when businesstype = 'Forecast' then amount end) as forecast,
sum(case when businesstype = 'Sales' then amount end) as sales
from t
group by yearmonth, customer, currency;
您可以進行聚合:
select yearmonth, customer, currency,
sum(case when businesstype = 'budget' then amount else 0 end),
sum(case when businesstype = 'Forecast' then amount else 0 end),
sum(case when businesstype = 'Sales' then amount else 0 end)
from table t
group by yearmonth, customer, currency;
此外,您可能需要添加“其他”來捕獲任何新的業務類型:
select yearmonth, customer, currency,
sum(case when businesstype = 'Budget' then amount end) as budget,
sum(case when businesstype = 'Forecast' then amount end) as forecast,
sum(case when businesstype = 'Sales' then amount end) as sales,
sum(case when businesstype not in ('Budget', 'Forecast', 'Sales') then amount end) as other
from t
group by yearmonth, customer, currency;
這種類型的要求通常使用 T-SQL PIVOT 關系操作來解決( https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql -server-ver15 )。 對於上面的示例,我使用以下查詢來實現此目的:
-- Create a temporary table to store the data.
IF (OBJECT_ID('tempdb..##temp2') IS NOT NULL) DROP TABLE ##temp2
CREATE TABLE ##temp2 (Id int IDENTITY (1,1) PRIMARY KEY, YearMonth varchar(100), Customer int, Currency varchar(100), BusinessType varchar(100), Amount int)
INSERT ##temp2
VALUES
('04-2020', 123,'EUR','Sales', 700),
('04-2020', 123,'EUR','Budget', 500),
('04-2020', 123,'EUR','Forecast', 300)
-- Using PIVOT allows you to move rows into columns
SELECT pivot_table.YearMonth,
pivot_table.Customer,
pivot_table.Currency,
[Amount Forecast] = pivot_table.Forecast,
[Amount Budget] = pivot_table.Budget,
[Amount Sales] = pivot_table.Sales
FROM
(
SELECT YearMonth,
Customer,
Currency,
BusinessType,
Amount
FROM ##temp2
) t
PIVOT
(
SUM(Amount)
FOR BusinessType IN ([Sales], [Budget], [Forecast])
) AS pivot_table;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.