合并两个查询

时间:2015-10-28 12:57:19

标签: subquery

我需要合并两个查询:一个列出每月所有项目的总和,一个列出YTD项目的总和。

我使用了工会,它可以在YTD'在我的下拉列表中选中。但是,当我选择任何其他月份时,它会给我YTD和所选月份的结果....

到目前为止的联合查询:

SELECT 
    Site.Site_Name 'Site', 
    'YTD' as 'Month_Name',
    Sum(MOT.Total_MR_Count_Received) 'Receiving', 
    Sum(MOT.Total_Line_Item_Count_Received) 'Checking', 
    Sum(MOT.Total_MR_Count_Shipped) 'Shipment Activity'

FROM 
    Metrics_Main 
    INNER JOIN Metrics_MOT MOT ON Metrics_Main.Metrics_Key = MOT.Metrics_Key 
    INNER JOIN Month ON Metrics_Main.Month_Key = Month.Month_Key 
    INNER JOIN Site ON Metrics_Main.Site_Key = Site.Site_Key

group by Site.site_name

union 

SELECT        
    Site.Site_Name 'Site', 
    Month.Month_Name 'Month_Name',          
    sum(MOT.Total_MR_Count_Received) 'Receiving',
    sum(MOT.Total_Line_Item_Count_Received) 'Checking',
    sum(MOT.Total_MR_Count_Shipped) 'Shipment_Activity'

FROM            
    Metrics_Main 
    INNER JOIN Metrics_MOT MOT ON Metrics_Main.Metrics_Key = MOT.Metrics_Key 
    INNER JOIN Month ON Metrics_Main.Month_Key = Month.Month_Key 
    INNER JOIN Site ON Metrics_Main.Site_Key = Site.Site_Key

WHERE        
    Month.Month_Name like @Month_Name

group by Site.site_name, month.month_name

1 个答案:

答案 0 :(得分:1)

这会有所帮助:http://www.w3schools.com/sql/sql_union.asp。确保您在两个选择查询中具有完全相同的列数;所以添加" Month_Name"也是第一个查询。