将包含文本的行移至列

时间:2019-02-27 18:03:51

标签: sql

我有一张像这样的桌子:

+----+---------+-------------+------------+
| 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(当Period = Past THEN Total_Units ELSE 0 END时的情况)作为Total_Units。

但是我不知道如何处理文本列。我已经看过一些枢轴和非枢轴子句,但是它们有时都使用聚合函数。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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'