SQL 多个逆轴
SQL multiples unpivot
我在使用多个 unpivot 时遇到了一些困难,也尝试了 APPLY。
所以假设我有:
[name] [Type1name] [Type2name] [Region1] [region2] [Type1valu] [type2value]
abc car bike US JP 500 300
def car boat US UK 150 200
ghi boat *null* BR *null* 50 *null*
now I want to aggregate [Type1name] + [Type2name] and [Region1] + [Region2] on same columns and values in each respective line:
[name] [Typename] [Region] [Value]
abc car US 500
abc bike JP 300
def car US 150
def boat UK 200
ghi boat BR 50
试试这个:
SELECT A.name, A.Type1name AS Typename, A.Region1 AS Region, A.Type1value AS 'Value'
FROM tableA A
WHERE A.Type1name IS NOT NULL
UNION ALL
SELECT A.name, A.Type2name AS Typename, A.Region2 AS Region, A.Type2value AS 'Value'
FROM tableA A
WHERE A.Type2name IS NOT NULL;
我在使用多个 unpivot 时遇到了一些困难,也尝试了 APPLY。 所以假设我有:
[name] [Type1name] [Type2name] [Region1] [region2] [Type1valu] [type2value]
abc car bike US JP 500 300
def car boat US UK 150 200
ghi boat *null* BR *null* 50 *null*
now I want to aggregate [Type1name] + [Type2name] and [Region1] + [Region2] on same columns and values in each respective line:
[name] [Typename] [Region] [Value]
abc car US 500
abc bike JP 300
def car US 150
def boat UK 200
ghi boat BR 50
试试这个:
SELECT A.name, A.Type1name AS Typename, A.Region1 AS Region, A.Type1value AS 'Value'
FROM tableA A
WHERE A.Type1name IS NOT NULL
UNION ALL
SELECT A.name, A.Type2name AS Typename, A.Region2 AS Region, A.Type2value AS 'Value'
FROM tableA A
WHERE A.Type2name IS NOT NULL;