2016-11-30 32 views
2

嗨,我有一個選擇幾個連接,我想顯示一個表中的所有行(RIGHT JOIN)。 這裏是我的查詢如何在表中使用一個右連接的少數連接SQL Server

MERGE #Players AS Target 
       USING (SELECT DT.[TimeId] AS [Selector],        
           [CurrencyId], 
           PT.Name         [ProductType], 
           COUNT(*) FirstTimeDepositors, 
           PT.Id FirstDepositProductTypeId 
         FROM [WarehouseMgmt].[DimPlayer] DP 
         JOIN [WarehouseMgmt].[DimTimeZone] DT ON DP.[FirstDepositTimeId] = DT.TimeUTCId 
         RIGHT JOIN [WarehouseMgmt].[DimProductType] PT ON PT.Id = DP.FirstDepositProductTypeId      
         AND [FirstDepositTimeId] BETWEEN @DimStartDateUTC AND @DimEndDateUTC 
         AND DP.[IsInternalAccount] = 0 
         GROUP BY DT.[TimeId],[CurrencyId],PT.Name,PT.Id) AS Source 
       ON (Target.[Time] = Source.[Selector] AND Target.[CurrencyId] = Source.[CurrencyId] AND Target.[ProductType] = Source.[ProductType]) 
       WHEN MATCHED THEN 
         UPDATE SET Target.[FirstTimeDepositorsCounts] = Source.[FirstTimeDepositors] 
       WHEN NOT MATCHED BY TARGET THEN 
         INSERT ([Time],[CurrencyId],[ProductType],[FirstTimeDepositorsCounts],[FirstDepositProductTypeId]) 
         VALUES (Source.[Selector],Source.[CurrencyId],[ProductType],Source.[FirstTimeDepositors],Source.[FirstDepositProductTypeId]); 

但是,這並不爲我工作很好,加上我想有WHERE子句,如果有可能與右連接

+0

誰使用'RIGHT JOIN'可好? – sagi

+0

我不知道誰在使用:)我需要一個解決方案,它將連接所有表並從DimProductType表中獲取所有ProductType。如果你知道一些更好的解決方案,歡迎:) – user2171512

回答

1

如果你要過濾的連接表,你可以添加它加入到連接子句或使用子查詢。

RIGHT JOIN [WarehouseMgmt].[DimProductType] PT 
    ON PT.Id = DP.FirstDepositProductTypeId And PT.Field = "What you want" 

RIGHT JOIN 
    (Select Fields From [WarehouseMgmt].[DimProductType] Where Field = "What you want") PT 
    ON PT.Id = DP.FirstDepositProductTypeId 
+1

哦,是的,我知道,哈哈:) –