【问题标题】:Get DISTINCT list of values within GroupBy sql获取 GroupBy sql 中的 DISTINCT 值列表
【发布时间】:2022-01-06 03:51:42
【问题描述】:

我有这张桌子

place  subplace   
A      x
A      x
B      x
A      y
B      y
A      y
A      z

当我做这个查询时

SELECT place, count(distinct subplace) AS count_subplace
from  table 
GROUP BY place

我得到结果

place count_subplace
A     3
B     2

现在我想要不同元素的列表而不是计数

我知道我们可以使用string_agg

如何在其中调用 distinct 和 groupby

我想要类似的结果

place subplace_list
A     x,y,z
B     x,y

这个我试过了,不行

SELECT place, string_agg(distinct subplace,',') AS list_subplace
from  table 
GROUP BY place

【问题讨论】:

  • 你的 dbms 怎么样?
  • 微软,Azure 数据工作室

标签: sql azure-sql-database


【解决方案1】:

因为string_agg里面不支持distinct

您可以尝试使用子查询来distinct 您的结果集。

查询 1

SELECT place, string_agg(subplace,',') AS list_subplace
from  (select distinct place,subplace from t) t1
GROUP BY place

Results

| place | list_subplace |
|-------|---------------|
|     A |         x,y,z |
|     B |           x,y |

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多