帮助编写 SQL 查询

发布于 2024-09-18 03:01:45 字数 419 浏览 10 评论 0原文

可能的重复:
需要帮助将相邻行合并为一行的 SQL 查询

这就是我的表的外观。

alt text

..我需要编写一个查询来获取如下输出:

alt text

这不是一个家庭作业问题。

Possible Duplicate:
Need help with a SQL query that combines adjacent rows into a single row

So this is how my table looks.

alt text

..and I need to write a query to get the output like this:

alt text

This is not a homework question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

も星光 2024-09-25 03:03:37

这个问题被问了很多次...
答案总是一样的。像这样的东西

SELECT Category, GROUP_CONCAT(PROD SEPARATOR ", ") AS Prod, SUM(Price) AS Amt FROM yourtable GROUP BY Category

应该没问题。

This question is asked many times...
The answer is always the same. Something like

SELECT Category, GROUP_CONCAT(PROD SEPARATOR ", ") AS Prod, SUM(Price) AS Amt FROM yourtable GROUP BY Category

should be ok.

一身骄傲 2024-09-25 03:03:13

用于测试的一些示例数据:

DECLARE @Sample TABLE (ID INT, Name VARCHAR(15), Price INT)

INSERT  @Sample
SELECT  1, 'Ford', 100 UNION ALL
SELECT  1, 'Cereal', 200 UNION ALL
SELECT  2, 'Fruits', 30 UNION ALL
SELECT  2, 'Fruits2',70 UNION ALL
SELECT  3, 'Soap', 40

SELECT * FROM @Sample

查询将是:

SELECT s3.ID, Stf.Conc, 
SUM(s3.Price) PriceSum
FROM @Sample s3 INNER JOIN (
SELECT DISTINCT s1.ID, 
       STUFF((SELECT ',' + s2.Name 
           FROM @Sample AS s2 
           WHERE s2.ID = s1.ID 
           FOR XML PATH('')), 1, 1, '') Conc 
       FROM @Sample s1) AS Stf
ON s3.ID = Stf.ID
GROUP BY s3.ID, Stf.Conc

Some sample data to test with:

DECLARE @Sample TABLE (ID INT, Name VARCHAR(15), Price INT)

INSERT  @Sample
SELECT  1, 'Ford', 100 UNION ALL
SELECT  1, 'Cereal', 200 UNION ALL
SELECT  2, 'Fruits', 30 UNION ALL
SELECT  2, 'Fruits2',70 UNION ALL
SELECT  3, 'Soap', 40

SELECT * FROM @Sample

And the query would be:

SELECT s3.ID, Stf.Conc, 
SUM(s3.Price) PriceSum
FROM @Sample s3 INNER JOIN (
SELECT DISTINCT s1.ID, 
       STUFF((SELECT ',' + s2.Name 
           FROM @Sample AS s2 
           WHERE s2.ID = s1.ID 
           FOR XML PATH('')), 1, 1, '') Conc 
       FROM @Sample s1) AS Stf
ON s3.ID = Stf.ID
GROUP BY s3.ID, Stf.Conc
独自←快乐 2024-09-25 03:02:55

以下答案仅适用于 SQL Server 2005+:

  SELECT t.category,
         STUFF((SELECT ','+ x.prod
                  FROM TABLE x
                 WHERE x.category = t.category
              GROUP BY x.prod
               FOR XML PATH('')), 1, 1, '') AS prod,
         SUM(t.price) AS amt
    FROM TABLE t
GROUP BY t.category

The following answer is only valid for SQL Server 2005+:

  SELECT t.category,
         STUFF((SELECT ','+ x.prod
                  FROM TABLE x
                 WHERE x.category = t.category
              GROUP BY x.prod
               FOR XML PATH('')), 1, 1, '') AS prod,
         SUM(t.price) AS amt
    FROM TABLE t
GROUP BY t.category
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文