2016-01-28 91 views
1

選擇一個列組我有表數據象下面這樣:MYSQL其他列

enter image description here

我想有以下的輸出:

enter image description here

其實我喜歡做這樣的事情:

select CustomerName, (select sum(Amount) from tbl where tbl.CustomerName = CustomerName) as Amount, consumedDate from tbl 

但由於數據被取出使用子查詢,所以我不能使用子查詢在SELECT語句來選擇金額:

select CustomerName, (select sum(Amount) from myTable where myTable.CustomerName = tbl.CustomerName) as Amount, consumedDate from (select CustomerName, Amount, ConsumedDate from myTable) as tbl 

上面的查詢將導致錯誤:

Table tbl doesn't exist 

有任何解決方法?

回答

2

我會建議使用變量用於這一目的。這需要兩次通過:

select customername, consumeddate, 
     (@a := if(@c = customername, @a, 
       if(@a := customername, cume_amount, cume_amount) 
       ) 
     ) amount 
from (select t.*, 
      (@a := if(@c = customername, @a + amount, 
         if(@c := customername, amount, amount) 
        ) 
      ) as cume_amount 
     from (<your subquery here>) t cross join 
      (select @c := '', @a := 0) params 
     order by customername 
    ) t cross join 
    (@ac := '', @a := 0) params 
order by customername, cume_amount desc; 

第一遍計算每個客戶的累計總和。第二個將最大值複製回客戶的所有行。

1
SELECT a.CustomerName, b.amt, a.consumedDate 
FROM tbl a, (
    SELECT CustomerName, sum(Amount) amt 
    FROM tbl 
    GROUP BY 1 
) as b 
WHERE a.CustomerName = b.CustomerName 

這裏是好學生的SQL:

SELECT a.CustomerName, b.Amount, a.consumedDate 
FROM tbl AS a 
JOIN (
    SELECT CustomerName, sum(Amount) Amount 
    FROM tbl 
    GROUP BY CustomerName 
) AS b ON a.CustomerName = b.CustomerName 
+3

不要在where子句中使用這種舊式連接它不鼓勵 –

+2

由於OP是一個複雜的子查詢,所以OP的要點是* not *來引用表。我可以理解答案,但不是upvotes(並且甚至擱置不好的連接語法)。 –

+0

感謝@JorgeCampos和goron-linoff,我將從今天起使用JOIN關鍵字 – SIDU