根据主选择查询值在where条件中选择查询

时间:2016-03-21 11:01:03

标签: mysql sql

我有三个这样的表: invoice_table

╔════╦════════════╦
║ id ║ invoice_id ║
╠════╬════════════╬
║  1 ║     1      ║
║  2 ║     2      ║
║  3 ║     3      ║
╚════╩════════════╩ 

bill_table

╔════╦════════════╦══════════╗
║ id ║ invoice_id ║bill_amt  ║
╠════╬════════════╬══════════╣
║  1 ║     1      ║   50     ║
║  2 ║     1      ║   80     ║  
║  3 ║     2      ║   25     ║
║  4 ║     2      ║   55     ║
║  5 ║     3      ║   60     ║
║  6 ║     3      ║   55     ║
╚════╩════════════╩══════════╝

credit_table

╔════╦════════════╦══════════╗
║ id ║ invoice_id ║credit_amt║
╠════╬════════════╬══════════╣
║  1 ║     1      ║   50     ║
║  3 ║     2      ║   25     ║
║  4 ║     2      ║   55     ║
║  5 ║     3      ║   60     ║
╚════╩════════════╩══════════╝

我需要所有invoice_id where(sum(credit_amt of the invoice_id)-sum(bill_amt of invoice_id))> 0 到目前为止我试过这个

select invoice_id from invoice_table where 
((select sum(bill_amt) FROM bill_table) - (select sum(credit_amt) FROM credit_table)) > 0

换句话说,我想要这个结果:

╔════════════╗
║ invoice_id ║
╠════════════╣
║     1      ║
║     3      ║
╚════════════╝

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT i.invoice_id
FROM invoice_table i 
    LEFT JOIN
    (SELECT invoice_id, SUM(bill_amt) AS sum_bill_amt 
     FROM bill_table
     GROUP BY invoice_id) b 
    ON i.invoice_id = b.invoice_id
    LEFT JOIN 
    (SELECT invoice_id, SUM(credit_amt) AS sum_credit_amt 
     FROM credit_table
     GROUP BY invoice_id) c 
    ON i.invoice_id = c.invoice_id
WHERE b.sum_bill_amt - c.sum_credit_amt > 0;

答案 1 :(得分:0)

DROP TABLE invoices;

CREATE TABLE invoices
(invoice_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY);

INSERT INTO invoices VALUES
(1),
(2),
(3);

DROP TABLE debits;

CREATE TABLE debits
(debit_id INT NOT NULL PRIMARY KEY
,invoice_id INT NOT NULL
,debit_amount INT NOT NULL
);

INSERT INTO debits VALUES
(1,1,50),
(2,1,80),
(3,2,25),
(4,2,55),
(5,3,60),
(6,3,55);

DROP TABLE credits;

CREATE TABLE credits
(credit_id INT NOT NULL
,invoice_id INT NOT NULL
,credit_amount INT NOT NULL
);

INSERT INTO credits VALUES
(1,1,50),
(3,2,25),
(4,2,55),
(5,3,60);

SELECT i.invoice_id
     , SUM(amount) total 
  FROM invoices i 
  JOIN
     ( SELECT invoice_id, credit_amount * -1 amount FROM credits
       UNION ALL
       SELECT invoice_id, debit_amount FROM debits
     ) x 
    ON x.invoice_id = i.invoice_id 
 GROUP 
    BY i.invoice_id
HAVING total > 0;

+------------+-------+
| invoice_id | total |
+------------+-------+
|          1 |    80 |
|          3 |    55 |
+------------+-------+