Select 查询 Sum 并将其分组

Select Query for Sum and group it

我对合并项目列感到困惑。请帮我做一下。

您真的应该更多地了解 SQL 并阅读您的具体数据库类型的文档 - SQL 不同数据库的查询略有不同。不过在 MySQL 你可以这样做:

SELECT GROUP_CONCAT(Item SEPARATOR ' | '), SUM(Qty), SUM(ST), SUM(Amt) FROM <supplier> GROUP BY Supplier;

其中 <供应商> 应替换为您的 table。

PostgreSQL 中的解决方案。请注意 distinct item.

select string_agg(distinct item, '|') items, supplier, 
       sum(qty) qty, sum(st) st, sum(amt) amt
from the_table 
group by supplier;

编辑
sql-server 数据库被标记后,我上面的回答不再相关。

Oracle/DB2/Snowflake中的解决方案SQL:
LISTAGG 函数符合 ANSI/SQL:2016 标准,但并非每个最新的 RDBMS 版本都普遍支持)

SELECT
 LISTAGG(Item, '|') WITHIN GROUP (ORDER BY Qty) AS Item, 
 Supplier, 
 SUM(Qty) AS Qty, 
 SUM(St) AS St, 
 SUM(Amt) AS Amt
FROM yourtable 
GROUP BY Supplier
ORDER BY Supplier

MS Sql Server 2014 的解决方案:

SELECT
 STUFF((select '|'+ t2.Item
        from yourtable t2
        where t2.Supplier = t.Supplier
        order by t2.Qty
        for xml path ('')),1,1,'') AS Item,
 Supplier, 
 SUM(Qty) AS Qty,
 SUM(St) AS St, 
 SUM(Amt) AS Amt
FROM yourtable t
GROUP BY Supplier
ORDER BY Supplier

MS Sql Server 2017+ 使用 STRING_AGG 的解决方案:

SELECT
 STRING_AGG(Item, '|') WITHIN GROUP (ORDER BY Qty) AS Item,
 Supplier, 
 SUM(Qty) AS Qty,
 SUM(St) AS St, 
 SUM(Amt) AS Amt
FROM yourtable t
GROUP BY Supplier
ORDER BY Supplier

您可以将此用于 SQL 服务器 < 2017

SELECT 
Supplier
,Items = STUFF((
        SELECT ' | ' + t2.Item
        FROM TestTable t2
        WHERE t.Supplier = t2.Supplier
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
,SUM(Qty) Qty
,SUM(ST) ST
,SUM(Amt) Amt
FROM TestTable t
GROUP BY Supplier