首页 > 解决方案 > 获取 SQLite 中 GROUP_CONCAT 的所有 id

问题描述

表 B

id   name     tablename
1    abc      table1    
2    xyz      table2
3    abc      table1
4    sdf      table2
5    dfg      table1 

询问:

SELECT B.tablename, GROUP_CONCAT(B.id),GROUP_CONCAT(B.name||'-'||cnt)
FROM (
    SELECT tablename, id, name, COUNT(*) cnt
    FROM B
    GROUP BY tablename,name
) B GROUP BY B.tablename

输出:

| tablename | GROUP_CONCAT(B.id) | GROUP_CONCAT(B.nameB||'-'||cnt) |
| ------ | ------------------ | ------------------------------- |
| table1 | 1,5                | abc-2,dfg-1                     |
| table2 | 2,4                | xyz-1,sdf-1                     |

但是在这里我没有得到完整的 ID,正如您在表 1 的输出中看到的那样。

我想要类似的东西:

| tablename | GROUP_CONCAT(B.id) | GROUP_CONCAT(B.nameB||'-'||cnt) |
| ------ | ------------------ | ------------------------------- |
| table1 | 1,3,5              | abc-2,df-1                      |
| table2 | 2,4                | xyz-1,sdf-1                     |

请帮我解决这个问题。

标签: sqlitegroup-concat

解决方案


您还应该在子查询中使用GROUP_CONCAT()s id

SELECT tablename, GROUP_CONCAT(id), GROUP_CONCAT(name||'-'||cnt)
FROM (
    SELECT tablename, GROUP_CONCAT(id) id, name, COUNT(*) cnt
    FROM B
    GROUP BY tablename, name
) 
GROUP BY tablename

请参阅演示


推荐阅读