简体   繁体   English

如何合并两个查询

[英]How to combine two queries

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 我尝试了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 我在输出中仅看到3列

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 ? 有什么办法可以以我想要的格式查看结果?

Since I don't know their relationship, I prefer to use UNION ALL . 因为我不知道他们的关系,所以我更喜欢使用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

You can UNION them in the following fashion: 您可以按以下方式UNION它们:

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. 或在逻辑允许的情况下使用UNION ALL

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

I would use FULL OUTER JOIN thus: 我将这样使用FULL OUTER JOIN

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM