SQL查询以汇总所有不同的值

时间:2018-05-21 16:34:00

标签: mysql sql

我有一张表格,其中包含有关市场的信息:

market_id | cashier_id | storekeeper_id

m1        | c1         | s1
m1        | c1         | s2
m1        | c1         | s9
m1        | c2         | s3
m2        | c7         | s5
m2        | c8         | s6

我也有桌子收银员:

cashier_id | salary

c1         | 1100
c2         | 1100
c3         | 1100
c7         | 1220
c8         | 1150

和表店主:

storekeeper_id | salary
s1         | 1000
s2         | 1000
s3         | 1000
s5         | 1050
s6         | 1100
s9         | 1100

我想写一个查询,查找每个市场的工资摘要(包括收银员和店主)。 结果应该是:

m1 6300
m2 4520

我尝试使用其他2个表加入表市场,并在工资上使用SUM(DISTINCT),但这不包括具有相同薪水的员工。有没有其他方法可以做到这一点?

4 个答案:

答案 0 :(得分:0)

你有一个非常非常糟糕的数据模型,除非你的意图是说某个收银员在一个市场上多次工作。

也就是说,你可以从数据中得到你想要的东西。 union all是你的朋友:

select m.market_id, sum(salary)
from ((select distinct m.market_id, c.cashier_id, NULL as storekeeper_id, c.salary
       from markets m join
            cashiers c
            on c.cashier_id = m.cashier_id
      ) union all
      (select distinct m.market_id, NULL, s.storekeeper_id, s.salary
       from markets m join
            storekeepers s
            on s.storekeeper_id = m.storekeeper_id
      )
     ) m
group by m.market_id

答案 1 :(得分:0)

select market_id, sum(salary) from (
    select market_id, sum(salary) salary from 
    (select distinct market_id, cashier_id
    from markets)a
    join cashier b on a.cashier_id=b.cashier_id
    group by market_id
    union all
    select market_id, sum(salary) from
    (select distinct market_id, storekeeper_id
    from markets
     )b
    join storekeeper c on b.storekeeper_id=c.storekeeper_id
    group by market_id)c
group by market_id

答案 2 :(得分:0)

您可以使用UNION来结合收银员和店主工资。从那里,一个简单的GROUP BY将为您提供您正在寻找的东西。

SELECT market_id, SUM(salary)
FROM (SELECT m.market_id, c.cashier_id, c.salary
      FROM market m
      INNER JOIN cashier c ON c.cashier_id = m.cashier_id
      UNION
      SELECT m.market_id, s.storekeeper_id, s.salary
      FROM market m
      INNER JOIN storekeeper s ON s.storekeeper_id = m.storekeeper_id) tmp
GROUP BY market_id

答案 3 :(得分:0)

SELECT k.mid, (sum(k.cs) + sum(k.s_sum))
from (SELECT market_id as mid, market.cashier_id as cid,
cashier.salary as cs, sum(storekeeper.salary) as s_sum
((from markets inner join cashier on markets.cashier_id=cashier.cashier_id) 
inner join storekeeper on markets.storekeeper_id=storekeeper.storekeeper_id)
group by markets.market_id,cashier.cashier_id) as k
group by k.mid;