简体   繁体   English

在一列到多列中选择不同的值

[英]Select distinct values one column into multiple columns

I have the following data: column 1 with many category and column 2 with values for each category. 我有以下数据:具有多个类别的列1和具有每个类别的值的列2。 I need to convert or pivot this information to show each value for category group across multiple columns. 我需要转换或旋转此信息以显示跨多列的类别组的每个值。

col1      col2
----------------
1         a    
2         b 
2         c
2         d
3         e
3         f 
4         g
4         h

And need this result: 并需要这个结果:

col1      col2     col3     col4   col5   col6   
-----------------------------------------------   
1         a
2         b         c       d
3         e         f 
4         g         h

There are no more than seven values per tb1 count(column 2) group(column 1). 每个tb1计数(第2列)组(第1列)最多有七个值。 All values from tb1 column 2 are different and about + 50 records. tb1列2中的所有值都不同,大约有50条记录。

You want to pivot your table, but your table doesn't currently contain the field that you want to pivot on ("col1", "col2", "col3", etc...). 您想透视表,但表当前不包含要透视的字段(“ col1”,“ col2”,“ col3”等)。 You need a row number, partitioned by col1. 您需要一个由col1分区的行号。 The Jet database does not provide a ROW_NUMBER function, so you have to fake it by joining the table to itself: Jet数据库不提供ROW_NUMBER函数,因此您必须通过将表与其自身连接来伪造它:

select t1.col1, t1.col2, count(*) as row_num
from [Sheet1$] t1
inner join [Sheet1$] t2 on t2.col1 = t1.col1 and t2.col2 <= t1.col2
group by t1.col1, t1.col2

Now you can pivot on row_num : 现在您可以在row_num旋转:

transform Min(x.col2) select x.col1
from(
    select t1.col1, t1.col2, count(*) as row_num
    from [Sheet1$] t1
    inner join [Sheet1$] t2 on t2.col1 = t1.col1 and t2.col2 <= t1.col2
    group by t1.col1, t1.col2
    )  x
group by x.col1
pivot x.row_num

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

相关问题 SELECT DISTINCT在一列上,在mysql中有多列 - SELECT DISTINCT on one column, with multiple columns in mysql 在一个列上选择不重复,并返回多个列 - Select distinct on one column with multiple columns returned Oracle SQL在一个查询中选择多列不同的值,并根据不同的值对每一列进行分页 - Oracle SQL select multiple columns distinct values in one query with pagination requirement for each column based on distinct value SQL从一列中选择不同的值,然后将SQL输出到多列 - SQL Select Distinct Values from one Column and Output SQL to Multiple Columns 在某一列上选择不重复,返回多行和多列 - Select distinct on one column, returning multiple rows and columns 在sql中选择只有一个不同列的多个列 - Select multiple columns with only one distinct column in sql 同时在多个列上选择不重复,并在PostgreSQL中保留一列 - Select distinct on multiple columns simultaneously, and keep one column in PostgreSQL 对一列进行 SELECT DISTINCT,返回多个其他列 (SQL Server) - SELECT DISTINCT on one column, return multiple other columns (SQL Server) 在Oracle中按一列选择不同,但也显示多列 - Select distinct by one column in Oracle but displaying multiple columns too OracleSQL-选择在一个列上具有DISTINCT的所有列 - OracleSQL - Select ALL columns with DISTINCT on one column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM