简体   繁体   English

SQL-将多列合并为具有更多行的一列

[英]SQL - Combine multiple columns into one column with more rows

I have a table with 20 columns that all display the same thing. 我有一个包含20列的表,它们都显示相同的内容。 I'm not sure why my company set it up like this, but I cannot make changes to the table. 我不确定为什么我的公司会这样设置,但是我无法对表进行更改。

With that in mind, here is what I need to do. 考虑到这一点,这是我需要做的。 I need to populate a drop down list with insurance company names. 我需要在下拉列表中填写保险公司名称。 Therefore I need to find unique values across the entire table. 因此,我需要在整个表中查找唯一值。

Using a Group By clause is out of the question because I need unique values across the entire table. 使用Group By子句是不可能的,因为我需要整个表的唯一值。 No single column contains all the possible values. 没有任何一栏包含所有可能的值。 My only thought was to combine all the columns of the table together. 我唯一的想法是将表的所有列组合在一起。 I've seen this done using two pipes ( || ). 我已经看到使用两个管道(||)完成了此操作。 But that concatenates the columns which does not help me. 但这将列连接起来对我没有帮助。

I need to join two (or twenty) columns together and add their rows together. 我需要将两个(或二十个)列连接在一起并将其行添加在一起。 Ie if I started out with 20 columns and 100 rows, I need to have one column with 2000 rows. 即,如果我以20列100行开始,那么我需要有一列2000行。 This way I can select unique values using the Group By clause. 这样,我可以使用Group By子句选择唯一值。

Any help would be greatly appreciated! 任何帮助将不胜感激!

Sample of what I'm trying to accomplish: 我要完成的样本:

Sample original table: 示例原始表:

    --Ins1-----Ins2---Ins3---Ins4-
    Medicaid-Medicare-------------
    ---------Medicaid-----No 485--
    Blue Cross--------------------
    -------Home Health----Medicare

Table I need to construct: 我需要构造的表:

    --Column1--
    -Medicaid--
    -----------
    Blue Cross-
    -----------
    -Medicare--
    -Medicaid--
    -----------
    Home Health
    -----------
    -----------
    -----------
    -----------
    -----------
    --No 485---
    -----------
    -Medicare--

Maybe my logic is wrong. 也许我的逻辑是错误的。 This is the only way I could see to find unique information across the entire table. 这是我看到的在整个表格中查找唯一信息的唯一方法。

If this is SQL Server, then it sounds like you need to use UNPIVOT to perform this transformation. 如果这是SQL Server,则听起来您需要使用UNPIVOT来执行此转换。

Sample UNPIVOT (See SQL Fiddle with Demo): 样本UNPIVOT(请参阅带有演示的SQL Fiddle ):

select ques, answer
FROM t1
unpivot
(
    answer
    for ques in (col1, col2, col3, col4)
) u

The UNPIVOT will transform your data from columns to rows. UNPIVOT会将您的数据从列转换为行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM