在 SQL 中将行转换为列 [英] Convert Rows Into Columns in SQL

查看:38
本文介绍了在 SQL 中将行转换为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ID  COLA    
-----------------------
A   value1      
B   value1
C   value1      

表 B

ID  DETAIL_ID   COL_X   COL_Y
A   0           foo     foo
A   1           bar     bar
B   0           foo     foo

我的预期是这样的

ID  COLA    COL_X_0 COL_X_1 COL_Y_0 COL_Y_1
A   value1  foo     bar     foo     bar
B   value1  foo     NULL    foo     NULL
C   value1  NULL    NULL    NULL    NULL

这意味着表 B 的行将是基于 DETAIL_ID 列的列值.

It means the rows of table B will be column values based on DETAIL_ID column.

我尝试为此编写查询,但由于跟随而无法成功.DetailID 值的数量不是固定长度.这意味着我不能硬编码列的名称.

I tried to write queries for this , but can't succeed due to following. Number of DetailID values will NOT be fixed-length.It means I can't hard-coded the name of the columns.

推荐答案

SQL 查询必须指定结果集的列.这是 SQL 的基础.甚至 PIVOT 也要求您的查询在将其发送到 RDBMS 之前指定列.

SQL queries must specify the columns of the result set. That's fundamental to SQL. Even PIVOT requires that your query specify the columns before you send it to the RDBMS.

因此,创建一个查询以如您所描述的那样将行作为列返回,并且可以根据需要适应任意数量的列,既困难又容易出错.

For that reason, it's difficult and error-prone to create a query that returns rows as columns as you describe, and can adapt as needed to any number of columns.

处理动态列必须是一个两阶段的过程.

一种选择是将两个阶段设为:

One option is to make the two stages be:

  1. 编写应用程序代码以根据数据中找到的不同值动态构建 SQL 查询.这需要额外的查询来发现存在哪些值,以便您可以构建查询.
  2. 执行 SQL 查询并检索结果.

另一种选择是将两个阶段设为:

The other option is to make the two stages be:

  1. 运行更简单的 SQL 查询,将行作为行提取,因为它们存储在数据库中.
  2. 编写应用程序代码以对结果进行后处理,根据找到的值将行中的各个值收集到一组扩展的列中.这不像第一个设计那样需要额外的查询.

这篇关于在 SQL 中将行转换为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆