2016-04-21 77 views
0

我有兩個表 表1看起來像這樣使用select情況

ID Repeats 
----------- 
A 1 
A 1 
A 0 
B 2 
B 2 
C 2 
D 1 

表2看起來像這樣

ID values 
----------- 
A 100 
B 200 
C 100 
D 300 

使用視圖我需要這樣的結果查詢兩個表來過濾數據

ID values Repeats 
------------------- 
A 100 NA 
B 200 2 
C 100 2 
D 300 1 

這意味着,我想要獨特的ID,其valuesRepeatsRepeats如果存在多個values而不是單個ID,則值應該顯示爲NA,並且在repeats存在單個值的情況下應該顯示Repeats值。

起初,我需要顯示的repeats的最大值,所以我嘗試了以下觀點

ALTER VIEW [dbo].[BookingView1] 
AS 
SELECT bv.*, bd2.Repeats FROM Table1 bv 
JOIN 
(
    SELECT distinct bd.id, bd.Repeats FROM table2 bd 
    JOIN 
    (
     SELECT Id, MAX(Repeats) AS MaxRepeatCount 
     FROM table2 
     GROUP BY Id 
    ) bd1 
    ON bd.Id = bd1.Id 
    AND bd.Repeats = bd1.MaxRepeatCount 
) bd2 
ON bv.Id = bd2.Id; 

,這將返回正確的結果,但試圖執行CASE當它未能返回唯一結果ID。請幫忙!!

回答

1

一種方法是使用outer apply

select t2.*, t1.repeats 
from table2 t2 outer apply 
    (select (case when max(repeats) = min(repeats) then max(repeats) 
        else 'NA' 
       end) as repeats 
     from table1 t1 
     where t1.id = t2.id 
    ) t1; 

有兩點需要注意:

  • 這假定repeats是一個字符串。如果它是一個數字,則需要將其轉換爲一個字符串。
  • repeats不爲空。
0

爲了完整起見,我使用了另一種方法,如果repeatsNULL,則可以使用。但是,Gordon's答案有一個更簡單的查詢計劃,應該是首選。

選項1(工程與NULL S):

SELECT 
    t1.ID, t2.[Values], 
    CASE 
     WHEN COUNT(*) > 1 THEN 'NA' 
     ELSE CAST(MAX(Repeats) AS VARCHAR(2)) 
    END Repeats 
FROM (
     SELECT DISTINCT t1.ID, t1.Repeats 
     FROM #table1 t1 
    ) t1 
    LEFT OUTER JOIN #table2 t2 
    ON t1.ID = t2.ID 
GROUP BY t1.ID, t2.[Values] 

選項2(不包含明確的子查詢,但不與NULL的工作):

SELECT DISTINCT 
    t1.ID, 
    t2.[Values], 
    CASE 
     WHEN COUNT(t1.Repeats) OVER (PARTITION BY COUNT(DISTINCT t1.Repeats), t1.ID) > 1 THEN 'NA' 
     ELSE CAST(t1.Repeats AS VARCHAR(2)) 
    END Repeats 
FROM #table1 t1 
    LEFT OUTER JOIN #table2 t2 
    ON t1.ID = t2.ID 
GROUP BY t1.ID, t2.[Values], t1.Repeats 

注: 如果table2具有此功能對於相同的ID,不同的values