0
votes

I have two queries

1)

select Year , Month, Sum(Stores) from ABC ;

2) 
select Year, Month , Sum(SalesStores) from DEF ; 

I want a result like :

 **Year, Month , Sum(Stores), Sum(SalesStores)**

How can I do it ?

I tried union & Union all

select Year , Month, Sum(Stores) from ABC union
select Year, Month , Sum(SalesStores) from DEF ; 

I see only 3 columns in the output

Year, Month Sum(Stores).

Here are the tables :

Year, Month Stores

Year Month SalesStores

Is there a way I can see the result in the format I would like to see ?

4
How are both queries related, are ABC and DEF linked via foreign key? - Tim Schmelter

4 Answers

0
votes

Since I don't know their relationship, I prefer to use UNION ALL.

SELECT  Year, 
        Month, 
        MAX(TotalStores) TotalStores, 
        MAX(TotalSalesStores) TotalSalesStores
FROM
        (
            SELECT  Year, Month, 
                    SUM(Stores) TotalStores, 
                    NULL TotalSalesStores 
            FROM    ABC
            UNION ALL
            SELECT  Year, Month, 
                    NULL TotalStores, 
                    SUM(SalesStores) TotalSalesStores 
            from    DEF 
        ) a
GROUP   BY Year, Month
0
votes

You can UNION them in the following fashion:

SELECT Year , Month, Sum(Stores)  As Stores, NULL As SalesStores from ABC 

UNION

SELECT Year , Month,  NULL As Stores, Sum(Stores) As SalesStores from ABC 

Or use UNION ALL if your logic allows it.

0
votes

Try:

SELECT Year, Month, SUM(TotalStores) as TotalAllStores, SUM(TotalSalesStore) as TotalAllSalesStore
FROM
(
 SELECT Year , Month, Sum(Stores) as TotalStores, 0 as TotalSalesStore from ABC union
 UNION ALL
 SELECT Year, Month , 0 as TotalStores, Sum(SalesStores) as TotalSalesStore from DEF 
) SalesByYearMonth
GROUP BY Year, Month
0
votes

I would use FULL OUTER JOIN thus:

SELECT ISNULL(x.[Year], y.[Year]) AS [Year],
ISNULL(x.[Month], y.[Month]) AS [Month],
x.Sum_Stores,
y.Sum_SalesStores
FROM (select Year , Month, Sum(Stores) AS Sum_Stores from ABC ...) AS x
FULL OUTER JOIN (select Year, Month , Sum(SalesStores) AS Sum_SalesStores from DEF ...) AS y
ON x.[Year] = y.[Year] AND x.[Month] = y.[Month]