How to add different columns from different tables?

老子叫甜甜 提交于 2019-12-25 06:26:16

问题


I just wanted to add different columns from different tables... Has anyone any idea on how to do that?

Consider I have 3 tables as below

  1. tv sales
  2. AC sales
  3. cooler sales

And the tables data as follows

1)Tv Sales

   Id    Date        NoOfSales   Totalamount

    1    03/05/2014     10         10000
    2    04/05/2014     20         20000
    3    05/05/2014     30         30000

2)Ac Sales

   Id    Date        NoOfSales   Totalamount

   1    03/05/2014     10         50000
   2    04/05/2014     20         60000
   3    05/05/2014     30         70000

3)cooler Sales

   Id    Date        NoOfSales   Totalamount

   1    03/05/2014     10         30000
   2    04/05/2014     20         60000
   3    05/05/2014     30         70000

Now I want to add the "Totalamount" from all the tables for a particular "date" for example I need totalamount on 03/05/2014 as 90000


回答1:


In MySQL, the easiest way to do this is with union all and aggregation:

select date, sum(totalamount) as TotalSales
from ((select date, totalamount from TvSales
      ) union all
      (select date, totalamount from AcSales
      ) union all
      (select date, totalamount from CoolerSales
      )
     ) t
group by date;

The reason you want to use union all is in case the dates are different in the various tables. A join makes it possible to lose rows.

Second, having three tables with the same format is an indication of poor database design. You should really have one table with the sales and a column indicating which type of product it refers to.




回答2:


You could solve your problem by making a union of the information you want to aggregate on the different tables and them sum the amounts. This would look like:

   SELECT t.Date,SUM(t.Totalamount)
    FROM
    (
      SELECT Date,Totalamount
      FROM tvSales
      UNION ALL
      SELECT Date,Totalamount
      FROM acSales
      UNION ALL
      SELECT Date,Totalamount
      FROM coolerSales
    ) t
    WHERE t.Date='03/05/2014'
    GROUP BY t.Date

It is important that the fields of the union have the same name and type. In case they haven't the same name you should create common aliases for the 2 columns across the 3 select queries and then work with these aliases on the main query. Also the UNION should be performed including the ALL keyword in order to avoid eliminating duplicate records across the three tables.



来源:https://stackoverflow.com/questions/23723637/how-to-add-different-columns-from-different-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!