2017-07-31 67 views
1

我有一個查詢,我想添加一個排名列。我現有的查詢有三個表作爲聯合查詢,其中有一週的總訂單價值。此查詢會生成按WeekCommencing分組的總訂單價值總和,但我很難根據該周的最高到最低總值添加排名列。按日期排列的值列的排名SUM

我(更新)SQLFiddle例子是這裏http://sqlfiddle.com/#!9/f1d43/35

CREATE和INSERT語句:

CREATE TABLE IF NOT EXISTS ORD (
    WeekCommencing DATE, 
    Value DECIMAL(20 , 6), 
    Orders INT(6) 
); 
CREATE TABLE IF NOT EXISTS REF (
    WeekCommencing DATE, 
    Value DECIMAL(20 , 6), 
    Orders INT(6) 
); 
CREATE TABLE IF NOT EXISTS SOH (
    WeekCommencing DATE, 
    Value DECIMAL(20 , 6), 
    Orders INT(6) 
); 

INSERT INTO ORD (WeekCommencing, Value, Orders) VALUES 
('2017-07-24',1,1), 
('2017-07-31',2,1), 
('2017-07-17',3,1); 

INSERT INTO REF (WeekCommencing, Value, Orders) VALUES 
('2017-07-24',4,1), 
('2017-07-17',5,1), 
('2017-07-31',6,1); 

INSERT INTO SOH (WeekCommencing, Value, Orders) VALUES 
('2017-07-17',7,1), 
('2017-07-24',8,1), 
('2017-07-31',9,1); 

我迄今爲止最好的努力:

SELECT 
    WeekCommencing, 
    SUM(Value) AS 'TotalValue', 
    SUM(Orders) AS 'Orders', 
    @r:[email protected]+1 As 'Rank' 
FROM 
    (SELECT 
     WeekCommencing, Value, Orders 
    FROM 
     ORD 
    GROUP BY WeekCommencing UNION ALL SELECT 
     WeekCommencing, Value, Orders 
    FROM 
     REF 
    GROUP BY WeekCommencing UNION ALL SELECT 
     WeekCommencing, Value, Orders 
    FROM 
     SOH 
    GROUP BY WeekCommencing) t1, 
    (SELECT @r:=0) Rank 
GROUP BY WeekCommencing DESC; 

我嘗試目前位列周的順序開始,而不是從最高排名到最低排名。

我期望的結果是

WeekCommencing TotalValue Orders Rank 
2017-07-31  17   3  1 
2017-07-24  13   3  3 
2017-07-17  15   3  2 

謝謝你是進步

回答

0
SELECT a.* 
    , @i:[email protected]+1 rank 
    FROM 
    (SELECT weekcommencing 
      , SUM(value) totalvalue 
      , COUNT(*) totalorders 
     FROM 
      (SELECT weekcommencing, value, orders FROM ord 
       UNION ALL 
       SELECT weekcommencing, value, orders FROM ref 
       UNION ALL 
       SELECT weekcommencing, value, orders FROM soh 
      ) x 
     GROUP 
      BY weekcommencing 
    ) a 
    , (SELECT @i:=0) vars 
ORDER 
    BY totalvalue DESC; 
+0

大。這顯示正確的排名。是否可以通過WeekCommencing獲得排名和訂單? – Walkertron

+0

只是把它包裹在另一個超級查詢 – Strawberry

+0

完美。現在已經排序了。 – Walkertron