SQL 将行值转换为列标题

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

我有下表:

tableA
+-----------+--------+
| tableA_id |  code  |
+-----------+--------+
|         1 | code A |
|         2 | code B |
|         3 | code A |
|         3 | code C |
|         3 | code B |
|         4 | code A |
|         4 | code C |
|         4 | code B |
|         5 | code A |
|         5 | code C |
|         5 | code B |
+-----------+--------+

我想使用查询将代码 A、代码 B、代码 C 显示为列标题,然后值将显示 tableA_id 条目在代码字段中是否包含该代码。所以像这样:

+-----------+------------------------------+
| tableA_id |  code A |  code B  |  code C |
+-----------+------------------------------+
|         1 |   yes   |          |         |
|         2 |         |   yes    |   yes   |
|         3 |   yes   |   yes    |   yes   |

etc...

你能用 SQL 做到这一点吗?

sql pivot crosstab
3个回答
5
投票

这个问题的挑战是

code
列可以包含任意值列表。通常 PIVOT 要求将
IN
内的值作为常量提供,尽管使用 Snowflake 可以使用
ANY
或子查询。

这种模式称为 “动态 PIVOT”:

SELECT *
FROM tableA
PIVOT (MIN(code) FOR code IN (ANY)) AS pvt
ORDER BY tableA_id;

enter image description here

带有子查询的版本:

SELECT *
FROM tableA
PIVOT (MIN(code) FOR code IN (SELECT code FROM tableA)) AS pvt
ORDER BY tableA_id;


以前的版本

使用条件聚合(不同方言之间可移植):

SELECT tableA_id,
       MAX(CASE WHEN code ='code A' THEN 'yes' END) AS "code A",
       MAX(CASE WHEN code ='code B' THEN 'yes' END) AS "code B",
       MAX(CASE WHEN code ='code C' THEN 'yes' END) AS "code C"
FROM tableA
GROUP BY tableA_id;

输出:

╔════════════╦═════════╦═════════╦════════╗
║ tableA_id  ║ code A  ║ code B  ║ code C ║
╠════════════╬═════════╬═════════╬════════╣
║         1  ║ yes     ║ (null)  ║ (null) ║
║         2  ║ (null)  ║ yes     ║ (null) ║
║         3  ║ yes     ║ yes     ║ yes    ║
║         4  ║ yes     ║ yes     ║ yes    ║
║         5  ║ yes     ║ yes     ║ yes    ║
╚════════════╩═════════╩═════════╩════════╝

有很多可能性(搜索):

PIVOT            -> SQL Server/Oracle
CROSSTAB         -> Postgresql
SELF OUTER JOIN  -> All
CONDITIONAL AGG  -> All
...

0
投票

您需要在 SQL 语法中使用类似的内容

Select *
From Table1
pivot ( Aggregate function For Column Name in ([CodeA], [CodeB] , [CodeC])) as PivotTable

0
投票

或者如果您想要动态 SQL 语句,您可以尝试以下操作。 您只需更改表和/或列的名称。

declare
cursor code is select code, rownum rn, count(*) over (partition by 1 ) as cnt from (select distinct code from test) order by 1;
build_Case clob;
a varchar2(100);
begin

for i in code loop
if i.rn <> i.cnt then
build_case := build_case || CHR(10) || ' max((case when code = ''' || i.code || ''' then ''yes'' else null end)) ' || i.code || ',';
else 
build_case := build_case || CHR(10) || ' max((case when code = ''' || i.code || ''' then ''yes'' else null end)) ' || i.code;
end if;
end loop;

build_case := 'select id,' || build_case || ' from test group by id';
dbms_output.put_line(build_Case);

--execute immediate build_Case;
end;
/
© www.soinside.com 2019 - 2024. All rights reserved.