Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据SQL中的列字段将SQL中的行转换为列_Sql_String_Pivot - Fatal编程技术网

如何根据SQL中的列字段将SQL中的行转换为列

如何根据SQL中的列字段将SQL中的行转换为列,sql,string,pivot,Sql,String,Pivot,嗨 我需要为给定ID创建别名为的摘录。 别名已作为行输入表中。但是,要求是将其添加到不同的列中,并按照所述为ID创建一行。需要实现这一点的是SQL。透视选项不起作用一个选项使用窗口函数和条件聚合: select id, max(case when not is_alias then firstname end) firstname, max(case when not is_alias then lastname end) lastname, max(case when

我需要为给定ID创建别名为的摘录。
别名已作为行输入表中。但是,要求是将其添加到不同的列中,并按照所述为ID创建一行。需要实现这一点的是SQL。透视选项不起作用

一个选项使用窗口函数和条件聚合:

select id,
    max(case when not is_alias then firstname end) firstname,
    max(case when not is_alias then lastname  end) lastname,
    max(case when is_alias and rn = 1 then firstname || ' ' || lastname end) alias1,
    max(case when is_alias and rn = 2 then firstname || ' ' || lastname end) alias2,
    max(case when is_alias and rn = 3 then firstname || ' ' || lastname end) alias3
from (
    select t.*,
        row_number() over(partition by id, is_alias order by ??) rn
    from mytable t
) t
group by id
注:

为了使列的顺序一致,您需要一个定义别名顺序的列;我把它表示为??在查询中

如果希望每个id处理三个以上可能的别名,可以向select子句添加更多条件表达式

您没有告诉您正在运行哪个数据库;这使用了一个尽可能便携的标准,但是:

我使用了标准的ANSI字符串连接运算符| |;并非所有的数据库都支持这一点

我将is_别名视为合法的布尔值,可以在条件表达式中使用;这可能也需要调整


基本上,您要做的是旋转您的表。这一总体思路可能会帮助您:

SELECT *
FROM
(
    SELECT VAR1, VAR2, VAR3
    FROM TABLE1
) AS ORG_TABLE PIVOT(<the operation you want done>[VAR] FOR <VAR> IN 

(<List of values>) 

AS PivotTable


您使用的是哪一个数据库,您尝试使用哪种查询,并且您也不应该以图像形式提供数据。请使用您正在运行的数据库标记您的问题:mysql、oracle、sqlserver。。。?