如何在 table 中显示 sql 类别下的产品

How to display products under Category in sql in a table

我有以下 table:

产品属于不同类别,我排除了输出:

喜欢的产品及其成本需要显示在类别下(对于类别成本值,我想显示产品总成本)。我通过使用汇总和分组尝试了不​​同的方法,但我没有得到异常输出。

使用 Rollup 你会这样做。

SELECT  COALESCE(product,category,'Total') Category,
        SUM(VALUE) cost
FROM    products
GROUP BY ROLLUP(category,product)

开始了:

示例数据:

CREATE TABLE #product (ID INT, Category VARCHAR(50), Product VARCHAR(50), Value INT)
INSERT INTO #product
VALUES(1,'Non-veg','Chicken',150),
(2,'Non-veg','Mutton',200),
(3,'Non-veg','Fish',220),
(4,'Non-veg','Prawns',250),
(5,'Veg','Gobi',100),
(6,'Veg','Parota',45),
(7,'Veg','vegbirani',150) 

查询使用 GROUP BY with ROLLUP

SELECT  Category, Product,
       SUM(Value) AS Value
FROM #product
GROUP BY Category, Product WITH ROLLUP

结果:

您可以进一步操纵结果:

SELECT  COALESCE(product,category,'Total') Category,
       SUM(Value) AS Value
FROM #product
GROUP BY Category, Product WITH ROLLUP

结果:

回答下面的评论:"is there any way to display Category first then Products"这似乎有效:

;WITH CTE AS (
SELECT  Category, Product,
       SUM(Value) AS Value,
      ROW_NUMBER() OVER (PARTITION BY Category ORDER BY Product  ) AS rn
FROM #product
GROUP BY Category, Product WITH ROLLUP)

SELECT  Category = COALESCE(A.product,A.category,'Total') , A.Value 
FROM CTE AS A 
ORDER BY ISNULL(A.category,'zzzzzz') ,rn

结果:

也许是这样的……没有给出你的确切输出,但它很接近……

Select category, product, sum(value) as value
From TableName
group by grouping sets ((category),(category, product))