繁体   English   中英

使用 SQL 中另一列的所有唯一值创建新列

[英]Create new column with all unique values from another column in SQL

我有下表:

>>> id   crop     grower    loc
0  11    maize    Lulu    Fiksi
1  13    maize    Lulu    Menter
2  05    maize    Felix   Hausbauch
3  04    apples   Lulu    Fiksi
4  02    apples   Meni    Linter
5  06    cotton   Delina  Marchi
6  12    cotton   Lexi    Tinta
7  16    cotton   Lexi    Ferta
...

我想创建一个新表,该表将显示唯一的作物名称、出现的作物数量,然后列出所有种植该作物的种植者,因此结果表应如下所示:

>>>     crop   total_count   growers
0       maize    3           Lulu, Felix
1       apples   2           Lulu,Meni
2       cotton   3           Delina, Lexi

我设法创建了一个表格,显示了没有种植者姓名的作物和总数量:

select "CROP",count(*) "totalCount"
from "table"
group by "CROP"
order by "totalCount" desc

我的问题是如何创建带有新列的新表,其中包含每种作物的唯一种植者列表(如示例中所示)。

GROUP_CONCAT 用于 MySQL,Snowflake 使用 LISTAGG:

create or replace table test (
    id int,
    crop varchar,
    grower varchar,
    loc varchar
);

insert into test values 
(11, 'maize', 'Lulu', 'Fiksi'),
(13, 'maize', 'Lulu', 'Menter'),
(5, 'maize', 'Felix', 'Hausbauch'),
(4, 'apples', 'Lulu', 'Fiksi'),
(2, 'apples', 'Meni', 'Linter'),
(6, 'cotton', 'Delina', 'Marchi'),
(12, 'cotton', 'Lexi', 'Tinta'),
(16, 'cotton', 'Lexi', 'Ferta');

select
    crop,
    count(1) as total_count,
    listagg(distinct grower, ', ') as growers
from test
group by crop
;

+--------+-------------+--------------+
| CROP   | TOTAL_COUNT | GROWERS      |
|--------+-------------+--------------|
| maize  |           3 | Lulu, Felix  |
| apples |           2 | Lulu, Meni   |
| cotton |           3 | Delina, Lexi |
+--------+-------------+--------------+

您可以根据您的数据库使用 GROUP_CONCAT() 或任何相关的乐趣

select "CROP",count(*) "totalCount",GROUP_CONCAT(grower) as growers
from "table"
group by "CROP"
order by "totalCount" desc

暂无
暂无

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

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