Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear All,
I have one issue to get the data from three table as below..

Table A
CustName Mth tbbTotal
XYZ 04 0.30

Table B
CustName Mth pendAmt
XYZ 05 0.30
XYZ 06 0.30
XYZ 07 0.30

Table C
custName Mth collAmt
XYZ 08 0.30

I have required result in following fortmat

custName Mth tbbAmt pendAmt collAmt
XYZ 04 0.30 0.00 0.00
XYZ 05 0.00 0.30 0.00
XYZ 06 0.00 0.30 0.00
XYZ 07 0.00 0.30 0.00
XYZ 08 0.00 0.00 0.30


Request to all expert please help me to get the above result.
Thanks in Advance.
Posted

Hi

You can use either union or union all for your tables in My SQL

See the Syntax below

SQL
(SELECT * FROM t1)
UNION [ALL]
(SELECT * FROM t2 )



If you want unique records from all the tables then you can use "Union" only, but if you want to use all the records with duplication of unique records from all the tables then you can use "Union All". When you are using "Union" or "Union All", the count of columns in all the tables should be same with matching their type also.

Hope this will help you.
 
Share this answer
 
Try joining the three table on CustName and Mth:

SQL
select a.CustName, a.Mth, a.tbbTotal, b.pendAmt, c.collAmt
from
Table_A a join Table_B b on (a.CustName = b.CustName and a.Mth = b.Mth)
join Table_C on (a.CustName = c.CustName and a.Mth = c.Mth)
 
Share this answer
 
Thanks for quick reply,
Sory to say, that your given sql not show propoer result. result set missing the value, due the inner join because month not matched in Table A , Table B and Table C. Still issue are pending..
 
Share this answer
 
Thanks to support all of you, finaly i got the solution as below..

select a.custName,a.mth,
(select tbbAmt from Table_A as X where x.custName=a.custName and x.mth=a.mth) as tbbAmt,
(select pendAmt from Table_B as X where x.custName=a.custName and x.mth=a.mth) as pendAmt,
(select collAmt from Table_C as X where x.custName=a.custName and x.mth=a.mth) as collAmt from
(select * from Table_A
union all
select * from Table_B
union all
select * from Table_C
) as a

Again thanks to all...
Have nice days

Sunil Kumar Singh


UPDATE (Sandeep):
I think you should not use the above query. It's too costly relative to one I had suggested. You can avoid inner/sub queries.
 
Share this answer
 
v3
Here you go...
SQL
SELECT 
   CustName, Mth, tbbTotal, 0 AS pendAmt, 0 AS collAmt
FROM 
   TableA

UNION 

SELECT
   CustName, Mth, 0 AS tbbTotal, pendAmt, 0 AS collAmt
FROM
   TableB

UNION 

SELECT
   CustName, Mth, 0 AS tbbTotal, 0 AS pendAmt, collAmt
FROM
   TableC
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900