gpt4 book ai didi

sql - PIVOT SQL - 指导

转载 作者:行者123 更新时间:2023-12-01 23:38:33 27 4
gpt4 key购买 nike

我有以下代码:

    SELECT * 
FROM
(
SELECT p.ProductID, pc.Name, ISNULL(p.Color, 'Uncolored') AS Color
FROM SalesLT.ProductCategory AS pc
INNER JOIN SalesLT.Product AS p ON pc.ProductCategoryID = p.ProductCategoryID
)
AS PPC
PIVOT (COUNT(ProductID) FOR COLOR IN ([Red], [Blue], [Black], [Silver], [Yellow], [Grey], [Multi], [Uncolored]))
AS ColorPivotTable

这给出了以下输出:

Results

我想知道对此应用总计列的最佳方法

期望的输出 Desired output

非常感谢您的任何反馈。

最佳答案

这是 CUBE() (or GROUPING SETS) calculation 的一个很好的例子, 结合 PIVOT representation , I had to write a blog post about it .

下面是可以生成您正在寻找的内容的解决方案:

WITH Bikes(Name, Colour) AS (
SELECT * FROM (
VALUES ('Mountain Bikes', 'Black'),
('Mountain Bikes', 'Black'),
('Mountain Bikes', 'Silver'),
('Road Bikes', 'Red'),
('Road Bikes', 'Red'),
('Road Bikes', 'Red'),
('Road Bikes', 'Black'),
('Road Bikes', 'Yellow')
) AS Bikes(Name, Colour)
)
SELECT
Name,
COALESCE(Red, 0) AS Red,
COALESCE(Blue, 0) AS Blue,
COALESCE(Black, 0) AS Black,
COALESCE(Silver, 0) AS Silver,
COALESCE(Yellow, 0) AS Yellow,
COALESCE(Grey, 0) AS Grey,
COALESCE(Multi, 0) AS Multi,
COALESCE(Uncoloured, 0) AS Uncoloured,
Total
FROM (
SELECT
Coalesce(Name, 'Total') Name,
COALESCE(Colour, 'Total') Colour,
COUNT(*) Count
FROM Bikes
GROUP BY CUBE (Name, Colour)
) AS t
PIVOT (
MAX(Count) FOR Colour IN (
Red, Blue, Black, Silver, Yellow, Grey, Multi, Uncoloured, Total
)
) AS p
ORDER BY CASE Name WHEN 'Total' THEN 1 ELSE 0 END, Name

SQLFiddle here

关于sql - PIVOT SQL - 指导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com