创建一个查询以获得两个相同的结果

Create one query to achieve same result of two

我想要获得包含教师、费用和佣金的月份列表。 费用包括支付给教师的分期付款和给定课程的价格。 佣金是 'commision per lessons' 和 'month prices' 的总和。

架构:

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

Fiddle: http://sqlfiddle.com/#!9/7247a/1

您的数据结构非常混乱。我不太确定不同的实体应该代表什么。但是,以下 returns 您想要的结果(参见 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;