按案例分组

时间:2015-06-26 15:05:35

标签: mysql sql group-by case

我需要一张这样的表:

enter image description here

然而WITH ROLLUP我得到了这个和总负载两次是错误的。 enter image description here

我正在使用mysql:

SELECT CASE
    WHEN x.MarginProc < 0 THEN '< 0'
    WHEN x.MarginProc = 0 THEN '= 0'
    WHEN x.MarginProc > 0 THEN '> 0'
END AS 'Range'
, SUM(x.MarginValue) AS 'MarginValue'
FROM Product t
JOIN (
SELECT d.ProdId
        , SUM(d.quantity * (d.ListPrice - d.Cost) AS 'MarginValue'
        , SUM(d.quantity * (d.ListPrice - d.Cost )) / SUM(d.quantity * d.ListPrice)) * 100 AS 'MarginProc'
FROM OrderDetails d
JOIN OrderHeader h
    ON d.DokId = h.DokId
WHERE h.Data BETWEEN startdate AND enddate
GROUP BY d.ProdId
) x
ON x.ProdId = t.ProdId
GROUP BY CASE
    WHEN x.MarginProc < 0 THEN '0. <= 0'
    WHEN x.MarginProc = 0  AND x.MarginProc <= 5 THEN '1. (0, 5>'
    WHEN x.MarginProc > 5  AND x.MarginProc <= 10 THEN '2. (5, 10>'
END;

任何解决方案?

0 个答案:

没有答案