【问题标题】:Create new column with all unique values from another column in SQL使用 SQL 中另一列的所有唯一值创建新列
【发布时间】:2021-12-27 08:54:53
【问题描述】:

我有下表:

>>> 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

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

【问题讨论】:

  • 你的数据库是什么?
  • @Shadiqur 我不明白这个问题。有表格的例子
  • 您使用的是哪种 DBMS 产品? “SQL”只是所有关系数据库都使用的一种查询语言,而不是特定数据库产品的名称。请为您使用的数据库产品添加tag。 Why should I tag my DBMS

标签: sql snowflake-cloud-data-platform string-aggregation


【解决方案1】:

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 |
+--------+-------------+--------------+

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 导致错误:SQL 编译错误:未知函数 GROUP_CONCAT
    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 2020-02-20
    • 1970-01-01
    • 2021-10-17
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多