搜索子行的值

时间:2017-09-13 17:46:42

标签: sql-server sql-server-2008

我有这样的事情:

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' 

在我看来,这是一种不切实际的做法。

2 个答案:

答案 0 :(得分: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?

答案 1 :(得分: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