从多个类似的表中获得独特性

时间:2015-03-03 18:07:12

标签: sql sql-server tsql

我有这个查询来连接几个表并获得不同的值,它看起来像这样:

SELECT DISTINCT [TrackingCode]
    ,[Opponent]
    ,CONCAT([TrackingCode], ' | ', [Opponent]) AS RowName
    ,[MultiYrEvent] 
    ,[Identifier]
FROM [BUDGET_FY2014].[dbo].[TrackingCodes]

INNER JOIN
(
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions]
    WHERE Report='2377010003'
) AS T
ON T.EventCode LIKE CAST(TrackingCodes.TrackingCode AS nvarchar(20))+'%'
ORDER BY TrackingCode ASC

工作正常。但是,相对于Transactions表,我有第一个和第二个年前相同模式的多个Transactions表,我希望看到所有三个表中的不同值。例如,如果我复制/粘贴此查询并将[Transactions]更改为[Transactions_Yr1][Transactions_Yr2],那么我会从这些表中获取所需的数据。但是,我想把三者结合起来。如果我尝试加入所有这些,我将得不到任何结果。我有点明白为什么这不起作用,但我不知道从哪里开始:

SELECT DISTINCT [TrackingCode]
    ,[Opponent]
    ,CONCAT([TrackingCode], ' | ', [Opponent]) AS RowName
    ,[MultiYrEvent] 
    ,[Identifier]
FROM [BUDGET_FY2014].[dbo].[TrackingCodes]

INNER JOIN
(
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions]
    WHERE Report='2377010003'
) AS T
ON T.EventCode LIKE CAST(TrackingCodes.TrackingCode AS nvarchar(20))+'%'

INNER JOIN
(
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions_Yr1]
    WHERE Report='2377010003'
) AS T1
ON T1.EventCode LIKE CAST(TrackingCodes.TrackingCode AS nvarchar(20))+'%'

INNER JOIN
(
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions_Yr2]
    WHERE Report='2377010003'
) AS T2
ON T2.EventCode LIKE CAST(TrackingCodes.TrackingCode AS nvarchar(20))+'%'

ORDER BY TrackingCode ASC

任何建议将不胜感激!

2 个答案:

答案 0 :(得分:5)

尝试使用UNION ALL子句,例如:

SELECT DISTINCT [FILDS] 
 FROM (
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions]
    WHERE Report='2377010003'

    UNION ALL

    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions_Yr1]
    WHERE Report='2377010003'

    UNION ALL

     SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions_Yr2]
    WHERE Report='2377010003'
    )

ORDER BY TrackingCode ASC

答案 1 :(得分:0)

您是否尝试将事务表联合起来? 参考:https://msdn.microsoft.com/en-us/library/ms180026.aspx

SELECT DISTINCT [TrackingCode]
    ,[Opponent]
    ,CONCAT([TrackingCode], ' | ', [Opponent]) AS RowName
    ,[MultiYrEvent] 
    ,[Identifier]
FROM [BUDGET_FY2014].[dbo].[TrackingCodes]

INNER JOIN
(
    SELECT * FROM(
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions]
    WHERE Report='2377010003'
) AS T
ON T.EventCode LIKE CAST(TrackingCodes.TrackingCode AS nvarchar(20))+'%'

Union
(
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions_Yr1]
    WHERE Report='2377010003'
) AS T1
ON T1.EventCode LIKE CAST(TrackingCodes.TrackingCode AS nvarchar(20))+'%'

Union
(
    SELECT * 
    FROM [BUDGET_FY2014].[dbo].[Transactions_Yr2]
    WHERE Report='2377010003'
) AS T2
ON T2.EventCode LIKE CAST(TrackingCodes.TrackingCode AS nvarchar(20))+'%'
)
ORDER BY TrackingCode ASC