Setting column values as column names in the SQL query result(将列值设置为 SQL 查询结果中的列名)
问题描述
我想读取一个表,该表的值将是 sql 查询结果的列名.例如,我将 table1 设为 ..
I wanted to read a table which has values which will be the column names of the sql query result. For example, I have table1 as ..
id col1 col2
----------------------
0 name ax
0 name2 bx
0 name3 cx
1 name dx
1 name2 ex
1 name3 fx
如果您看到 id = 0,则 name 的值为 ax,name2 为 bx,name3 为 cx.将列显示为 id、name、name2、name3 会更容易,而不是行.现在我希望查询的结果如下所示:
If you see for id = 0, name has value of ax and name2 is bx and name3 is cx. Instead of this being rows it would be easier to show columns as id, name, name2, name3. Now I want the result of the query to look like this:
id name name2 name3
0 ax bx cx
1 dx ex fx
有人可以帮助我实现这一目标吗?
Can someone help me in achieving this?
推荐答案
这是通过数据透视表完成的.按 id
分组,您为要在列中捕获的每个值发出 CASE
语句,并使用类似 MAX()
聚合来消除空值并折叠到一行.
This is done with a pivot table. Grouping by id
, you issue CASE
statements for each value you want to capture in a column and use something like a MAX()
aggregate to eliminate the nulls and collapse down to one row.
SELECT
id,
/* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
/* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
FROM
yourtable
GROUP BY id
ORDER BY id
这是一个工作示例
注意:这仅适用于 col1
的有限且已知数量的可能值.如果可能值的数量未知,则需要在循环中动态构建 SQL 语句.
Here's a working sample
Note: This only works as is for a finite and known number of possible values for col1
. If the number of possible values is unknown, you need to build the SQL statement dynamically in a loop.
这篇关于将列值设置为 SQL 查询结果中的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将列值设置为 SQL 查询结果中的列名


基础教程推荐
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01