我有这张桌子:
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中实现吗?
答案 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;