2017-09-13 33 views
0

我有這樣的事情:搜索子行的值

Transaction Customer 
1    Cust1 
2    Cust2 
3    Cust3 
4    Cust4 

TransID  Code 
2   A 
2   B 
2   D 
3   A 
4   B 
4   C 

如果我希望能夠做一些像「如果客戶‘Cust1’有代碼‘A’」,我應該怎麼最好的建立視圖?我想最終能夠查詢像「從某些代碼列表中查看代碼的地方選擇客戶」或「從[某些代碼列表]中選擇代碼的視圖中選擇Cust1」

雖然我可以做像

Customer  | Codes 
Cust1   | A, B, D 
Etc. 

SELECT Transaction from Tbl where Codes like 'A' 

這對我來說似乎是不切實際的做法。

+1

請分享您的預期結果 – TheGameiswar

+0

@TheGameiswar這就是問題所在,我不確定我應該擁有什麼。我可以做一些像'TransID |代碼1 |代碼2 |代碼3 ...'但這似乎不切實際。 –

+1

那麼如果你不知道預期的結果應該是什麼,那麼我們怎麼能對它進行編碼呢?你試圖在這裏找到/回答的真正問題是什麼? – scsimon

回答

1

以下是我會做它

;with xact_cust (xact, cust) as 
(
    select 1, 'cust1' union all 
    select 2, 'cust2' union all 
    select 3, 'cust3' union all 
    select 4, 'cust4' 
), xact_code (xact, code) as 
(
    select 2, 'A' union all 
    select 2, 'B' union all 
    select 2, 'D' union all 
    select 3, 'A' union all 
    select 4, 'B' union all 
    select 4, 'C' 
) 
select Cust, Code 
from xact_cust cust 
inner join xact_code code 
    on cust.xact = code.xact 
where exists (select 1 
       from xact_code i 
       where i.xact = code.xact 
        and i.code = 'A') 

如果您需要序列化到一個分隔的列表代碼,看看這篇文章:What this query does to create comma delimited list SQL Server?

+0

好的,這是有道理的,這正是我沒有正確要求的,我只是添加一個'cust'組來爲每一行添加我想要的代碼。 –

1

這裏的另一種選擇......

IF OBJECT_ID('tempdb..#CustomerTransaction', 'U') IS NOT NULL 
DROP TABLE #CustomerTransaction; 

CREATE TABLE #CustomerTransaction (
    TransactionID INT NOT NULL PRIMARY KEY, 
    Customer CHAR(5) NOT NULL 
    ); 
INSERT #CustomerTransaction (TransactionID, Customer) VALUES 
    (1, 'Cust1'), (2, 'Cust2'), (3, 'Cust3'), 
    (4, 'Cust4'), (5, 'Cust5'); 

IF OBJECT_ID('tempdb..#TransactionCode', 'U') IS NOT NULL 
DROP TABLE #TransactionCode; 

CREATE TABLE #TransactionCode (
    TransactionID INT NOT NULL, 
    Code CHAR(1) NOT NULL 
    ); 
INSERT #TransactionCode (TransactionID, Code) VALUES 
    (2, 'A'), (2, 'B'), (2, 'D'), (3, 'A'), (4, 'B'), (4, 'C'); 

--SELECT * FROM #CustomerTransaction ct; 
--SELECT * FROM #TransactionCode tc; 
--============================================================= 

SELECT 
    ct.TransactionID, 
    ct.Customer, 
    CodeList = STUFF(tcx.CodeList, 1, 1, '') 
FROM 
    #CustomerTransaction ct 
    CROSS APPLY (
       SELECT 
        ', ' + tc.Code 
       FROM 
        #TransactionCode tc 
       WHERE 
        ct.TransactionID = tc.TransactionID 
       ORDER BY 
        tc.Code ASC 
       FOR XML PATH('') 
       ) tcx (CodeList); 

結果...

TransactionID Customer CodeList 
------------- -------- ----------- 
1    Cust1 NULL 
2    Cust2  A, B, D 
3    Cust3  A 
4    Cust4  B, C 
5    Cust5 NULL 
+0

我需要使用類似的運算符來進一步查詢這些結果嗎? –

+1

@PatrickSchomburg - No.您希望通過向外部查詢添加WHERE子句來過濾事務或客戶...或添加到子查詢中現有的WHERE中以過濾代碼。 –