创建一个查询以实现两个相同的结果

时间:2015-09-26 10:42:32

标签: mysql sql join group-by having

我希望获得有教师,费用和佣金的月份清单。 费用包含支付给教师的分期付款和赠送课程的价格。 Commision是“每节课”和“月价”的总和。

架构:

CREATE TABLE contract
    (`id` int, `teacher` varchar(64), `lesson_price` int, `lesson_price_commision` int, `month_price` int)
;

INSERT INTO contract
    (`id`, `teacher`, `lesson_price`, `lesson_price_commision`, `month_price`)
VALUES
    (1, 'John', 50, 10, 0),
    (2, 'Paul', 40, 15, 0),
    (3, 'Meg', 0, 0, 800)
;

CREATE TABLE installment
    (`id` int, `contract` int, `installment_price` int, `installment_date` date)
;

INSERT INTO installment
    (`id`, `contract`, `installment_price`, `installment_date`)
VALUES
    (1, 1, 300, '2015-09-28'),
    (2, 1, 400, '2015-09-30'),
    (3, 3, 500, '2015-09-28')
;

CREATE TABLE lesson
    (`id` int, `contract` int, `lesson_date` date)
;

INSERT INTO lesson
    (`id`, `contract`, `lesson_date`)
VALUES
    (1, 1, '2015-08-16'),
    (2, 3, '2015-09-01'),
    (3, 2, '2015-09-02'),
    (4, 1, '2015-09-06')
;

我在两个查询中创建了它,但我必须将它们组合在一起。

查询一个:

SELECT teacher, SUM(lesson_price_commision) AS commision, SUM(lesson_price) AS expense
FROM contract
JOIN lesson ON contract.id=lesson.contract 
WHERE MONTH(lesson_date) = 9 AND YEAR(lesson_date) = 2015
GROUP BY teacher

查询二:

SELECT teacher, SUM(month_price) AS commision, SUM(installment_price) AS expense
FROM installment
JOIN contract ON contract.id=installment.contract 
WHERE MONTH(installment_date) = 9 AND YEAR(installment_date) = 2015
GROUP BY teacher

我构建了这个:

SELECT teacher,
       (SUM(lesson_price_commision) + SUM(month_price)) AS commision,
       (SUM(lesson_price)+SUM(installment_price)) AS expense
FROM contract
  JOIN lesson ON contract.id=lesson.contract 
  LEFT JOIN installment ON installment.contract = contract.id
WHERE (MONTH(installment_date) = 9 AND YEAR(installment_date) = 2015)
   OR (MONTH(lesson_date) = 9 AND YEAR(lesson_date) = 2015)
GROUP BY teacher

结果是:

teacher | comission | expense
-----------------------------
John    |    40     |  1600
Paul    |    15     |  null
Meg     |   800     |   500

但我期待:

teacher | comission | expense
-----------------------------
John    |    10     |  750
Paul    |    15     |   40
Meg     |    800    |  500

小提琴:http://sqlfiddle.com/#!9/7247a/1

1 个答案:

答案 0 :(得分:1)

您的数据结构非常混乱。我不太确定不同的实体应该代表什么。但是,以下内容会返回您想要的结果(请参阅here):

SELECT c.teacher, (c.lesson_price_commision + c.month_price) as commission,
       (c.lesson_price + coalesce(i.expense, 0) ) as expense
FROM contract c LEFT JOIN
     (SELECT c.teacher, sum(installment_price) as expense
      FROM lesson l JOIN
           installment i
           ON i.contract = l.contract join
           contract c
           ON i.contract = c.id
      WHERE l.lesson_date >= '2015-09-01' and  l.lesson_date < '2015-10-01'
      GROUP BY c.teacher
     ) i
     ON c.teacher = i.teacher;