MYSQL按其他列选择一个列组

时间:2016-01-28 02:46:59

标签: mysql sql

我的表格包含以下数据:

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语句中使用子查询来选择Amount:

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 个答案:

答案 0 :(得分: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 :(得分:1)

<pre>

以下是优秀学生的SQL:

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