将包含Text的行转置为列

问题描述 投票:0回答:2

我有一张像这样的桌子:

+----+---------+-------------+------------+
| ID | Period  | Total Units |   Source   | 
+----+---------+-------------+------------+
|  1 | Past    |         400 | Competitor | 
|  1 | Present |         250 | PAWS       |  
|  2 | Past    |           3 | BP         | 
|  2 | Present |          15 | BP         |  
+----+---------+-------------+------------+

而且我正在尝试将行转换为列,因此对于每个ID,我有一个唯一的行来比较过去和现在的数字和属性。如下:

+----+------------------+---------------------+-------------+----------------+
| ID | Total Units Past | Total Units Present | Source Past | Source Present |
+----+------------------+---------------------+-------------+----------------+
|  1 |              400 |                 250 | Competitor  | PAWS           
|
|  2 |                3 |                  15 | BP          | BP             |
+----+------------------+---------------------+-------------+----------------+

转置总单位不是问题,因为我使用SUM(CASE WHEN Period =过去THEN Total_Units ELSE 0 END)AS Total_Units。

但是我不知道如何处理文本列。我已经看到使用了一些pivot和unpivot子句,但它们在某些时候都使用了聚合函数。

sql
2个回答
0
投票

你可以做条件聚合:

select id,
       sum(case when period = 'past' then units else 0 end) as unitspast,
       sum(case when period = 'present' then units else 0 end) as unitpresent,
       max(case when period = 'past' then source end) as sourcepast,
       max(case when period = 'present' then source end) as sourcepresent
from table t
group by id;

0
投票

假设每个ID只有两行,您也可以加入:

Select a.ID, a.units as UnitsPast, a.source as SourcePast
     , b.units as UnitsPresent, b.source as SourcePresent
from MyTable a
left join MyTable b
on a.ID = b.ID
and b.period = 'Present'
where a.period = 'Past'
© www.soinside.com 2019 - 2024. All rights reserved.