MySql选择显示按条件分组的总数

时间:2016-01-18 22:18:40

标签: mysql select

我有这张桌子:

SALESMAN |   INVOICE     |   VALUE   
1        |   7470        |   10       
1        |   7471        |   20       
1        |   7472        |   30     
2        |   7473        |   40       
2        |   7474        |   50       

我想要一个查询来获得这个结果:

SALESMAN |   INVOICE     |   VALUE   |  TOTAL_VALUE  | TOTAL_ITEMS
1        |   7470        |   10      |  40           | 3
1        |   7471        |   20      |  40           | 3
1        |   7472        |   10      |  40           | 3
2        |   7473        |   40      |  90           | 2
2        |   7474        |   50      |  90           | 2

TOTAL_VALUE是同一VALUE的所有SALESMAN的总和。 TOTAL_ITEMS是具有相同SALESMAN的行数。

可以在MySql中实现吗?

2 个答案:

答案 0 :(得分:1)

此查询:

SELECT SALESMAN, INVOICE , VALUE,  
(select sum(VALUE) FROM your_table t1 where t1.SALESMAN = your_table.SALESMAN) 
AS TOTAL_VALUE, 
(select count(VALUE) FROM your_table t2 where t2.SALESMAN = your_table.SALESMAN) 
AS TOTAL_ITEMS 
from your_table 

答案 1 :(得分:1)

使用GROUP BY

SELECT s.SALESMAN, s.INVOICE, s.VALUE,
xx.TOTAL_VALUE, xx.TOTAL_ITEMS
FROM sales s JOIN
(SELECT SALESMAN,
    SUM(VALUE) AS TOTAL_VALUE,
    COUNT(value) AS TOTAL_ITEMS
    FROM sales
    GROUP BY SALESMAN) xx ON S.SALESMAN = xx.SALESMAN;