从具有关系的多个表中选择数据

时间:2018-05-15 09:16:45

标签: sql mysqli

我需要从具有关系的多表中选择数据 A-> B-> C(A与B具有一对多关系,B与C具有多对一关系)。 As in given Picture of Database, I need to select sum of total_amount from petty_claim and vendors_claim on a specific Expense type and specific office(Invoice_main) group by Month(Invoice_main.date) click here to view picture 给定以下是没有实际值但与原始表类似的示例性表。所有值都是随机的 需要帮助。谢谢你的时间

Table: Invoice_main
Columns:   invoice_ID   Office_ID    Date
row:       1            2            2018-05-5
row:       2            1            2018-04-4
row:       3            1            2018-05-3

Table: Office
Columns:   office_ID   Office
row:       1            Support
row:       2            HR
row:       3            Billing

Table: Petty_claim
Columns:   invoice_id   Expense_id    Amount
row:       1            2             1000
row:       2            3             1000

Table: Vendors_claim
Columns:   invoice_id   Expense_id    Amount
row:       3            1             2000
row:       4            3             2000

Table: Expense_Types
Columns:   expense_id   dept_id
row:       1            Type A
row:       2            Type B
row:       3            Type C

OUT PUT必需

Month    Expense_Type   Office_1    Office_2 
1        Type A         1000        2000
2        Type B         2033        1034

1 个答案:

答案 0 :(得分:0)

会是这样的:

 SELECT SUM(invoice.total_amount)
  FROM (SELECT date, total_amount
          FROM invoice_main main , invoice_petty_claim petty, invoice_expense_type expense_type
         WHERE main.office = 'XXX' and main.id=petty.invoice_id and petty.expense_type = expense_type.type
         UNION ALL
        SELECT date, total_amount
          FROM invoice_main main, invoice_vendors_claim vendor, invoice_expense_type expense_type
         WHERE main.office = 'XXX' and main.id=vendor.invoice_id AND vendor.expense_type = expense_type.type
         ) invoice
 GROUP BY invoice.date