从MySQL中的四个或更多表中获取价值

时间:2017-11-12 12:11:42

标签: mysql sql join

我想从Four表中获取值并在GridView中显示如下:

enter image description here

我设法获得每个表的总数,但结果在一列下。如何在列中生成每个结果?

enter image description here
这是我从每个表中获得总数的查询:

{{1}}

2 个答案:

答案 0 :(得分:2)

转换查询以提供所需内容的最简单方法是:

SELECT 
    (
        select SUM(Amount_income_table)
        from bacci.income_table
        where year(Date_income_table)='2017'
    ) AS `Actual Income`,
    (
        select SUM(estimated_amount)
        from bacci.estimated_income_table
        where estimated_year='2017'
    ) AS `Estimated Income`,
    (
        select SUM(Amount_expenses_table)
        from bacci.expenses_table
        where year(Date_expenses_table)='2017'
    ) AS `Actual Expenses`,
    (
        select SUM(estimated_amount)
        from bacci.estimated_expenses_table
        where estimated_year='2017'
    ) AS `Estimated Expenses`;

答案 1 :(得分:0)

您似乎想要:

select 'Total Income' as which,
        (select sum(Amount_income_table) 
         from bacci.income_table
         where year(Date_income_table) = 2017
        ) as actual,
        (select sum(estimated_amount) 
         from bacci.estimated_income_table
         where estimated_year = 2017
        ) as estimated
union all
select 'Total Expense' as which,
        (select sum(Amount_expenses_table) 
         from bacci.expenses_table
         where year(Date_expenses_table) = 2017
        ) as actual,
        (select sum(estimated_amount) 
         from bacci.estimated_expenses_table
         where estimated_year = 2017
        ) as estimated

然后,您可以获得总计,并获得额外的聚合级别:

select which, sum(actual) as actual, sum(estimated) as estimated
from ((select 'Total Income' as which,
              (select sum(Amount_income_table) 
               from bacci.income_table
               where year(Date_income_table) = 2017
              ) as actual,
              (select sum(estimated_amount) 
               from bacci.estimated_income_table
               where estimated_year = 2017
              ) as estimated
      ) union all
      (select 'Total Expense' as which,
              (select sum(Amount_expenses_table) 
               from bacci.expenses_table
               where year(Date_expenses_table) = 2017
              ) as actual,
              (select sum(estimated_amount) 
               from bacci.estimated_expenses_table
               where estimated_year = 2017
              ) as estimated
      )
     ) ae
group by which with rollup