SQL - UNION ALL而不是JOIN

时间:2018-02-04 20:01:20

标签: sql sql-server

有人可以帮我弄清楚如何使用UNION ALL编写此脚本吗?目前,它使用JOIN代替UNION ALL

SELECT
    ISNULL(#vol2016.Destination, #vol2017.Destination) AS [Destination],
    ISNULL(#vol2016.[Volume 2016],0) AS [Volume 2016],
    ISNULL(#vol2017.[Volume 2017],0) AS [Volume 2017],
    ISNULL(#vol2017.[Volume 2017],0) - ISNULL(#vol2016.[Volume 2016],0) AS [Developement]
FROM(
    SELECT
        [year], [Destination], CAST(SUM([Volume]) as INT) as [Volume 2016] 
    FROM [dbo].[dw_lc_full_aggregated_1]
    WHERE [entry_type] = 'Country upload'
    AND [year]='2016'
    GROUP BY [year], [Destination]) #vol2016
FULL JOIN    
(SELECT
     [year], [Destination], CAST(SUM([Volume]) as INT) as [Volume 2017]
 FROM [dbo].[dw_lc_full_aggregated_1]
 WHERE [entry_type] = 'Country upload' AND [year]='2017'
 GROUP BY [year], [Destination]) #vol2017
ON [#vol2016].Destination=[#vol2017].Destination

所以输出应该是三列。目的地,2016年第卷,2017年。

2 个答案:

答案 0 :(得分:1)

使用此查询:

SELECT [year]
     , [Destination]
     , CAST(SUM([Volume]) as INT) AS [Volume]
  FROM
    (
        SELECT [year]
             , [Destination]
             , [Volume]
          FROM [dbo].[dw_lc_full_aggregated_1]
         WHERE [entry_type] = 'Country upload' AND [year]='2016'

        UNION ALL

        SELECT  [year]
              , [Destination]
              , [Volume]
          FROM  [dbo].[dw_lc_full_aggregated_1]
         WHERE  [entry_type] = 'Country upload' AND [year]='2017'
    ) AS T
GROUP BY [year],[Destination]

答案 1 :(得分:0)

可以 使用条件聚合CASE内的SUM()语句)让自己的生活变得更加简单

SELECT
    [Destination],
    [Volume_2016],
    [Volume_2017],
    [Volume_2017] - [Volume_2016]   AS [Development]
FROM
(
    SELECT
        [Destination],
        CAST(SUM(CASE WHEN [year] = '2016' THEN [Volume] END) as INT) [Volume_2016],
        CAST(SUM(CASE WHEN [year] = '2017' THEN [Volume] END) as INT) [Volume_2017]
    FROM
        [dbo].[dw_lc_full_aggregated_1]
    WHERE
            [entry_type] =  'Country upload'
        AND [year]       IN ('2016', '2017')
    GROUP BY
        [Destination]
)
    AS pivoted_agreggate

编辑: [Year]已从GROUP BY 中删除(复制并粘贴错误)