多表连接操作中的问题

时间:2015-01-19 07:43:40

标签: sql sql-server sql-server-2008

我有两张表 tbLicence tbLicenceTypes

tbLicence有三个字段AgentId LineOfAuthority,LicenceTypes

tbLicence 包含

等数据
AgentId          LineOfAuthority                  LicenceTypes
.........      ....................               ................ 
 287       Bail Bond,Casualty,Dental Services         1
 287       Casualty,Industrial Fire,Life              4
 287       Industrial Fire,Life                       4

tbLicenceTypes 有两个字段LicenceTypes,LicenceTypesX

tbLicenceTypes 包含

等数据
 LicenceTypes    LicenceTypesX   
 ............    .............
     1           Producer
     2          Sales Representative
     3          Insurance Agent
     4          Title Agent

现在我想获取分配给Casualty的所有许可类型。我的意思是AgentId是287,权限是伤亡人员......预期的输出应该是这样的

LicenceTypes    LicenceTypesX
...........    ...............
      1          Producer
      4         Title Agent

我尝试过下面的代码行......它没有工作

;WITH cte AS (
SELECT 
    AgentId,
    CAST('<r>' + REPLACE(REPLACE(LineOfAuthority,'&','&amp;'), ',', '</r>  <r>') + '</r>' AS XML) AS LineOfAuthoritys
FROM tbLicence
 )
,FinalList AS (
SELECT 
AgentId,
RTRIM(LTRIM (PTable.PColumn.value('.', 'VARCHAR(MAX)'))) AS LineOfAuthoritys
FROM cte
CROSS APPLY LineOfAuthoritys.nodes('//r') AS PTable(PColumn) 
)
SELECT DISTINCT 
   T.LicenceTypes AS LicenceTypes ,
   F.LineOfAuthoritys AS LicenceTypesX  
  FROM FinalList F
  CROSS APPLY (SELECT LicenceTypes FROM tbLicenceTypes TP WHERE            TP.LicenceTypesX = f.LineOfAuthoritys) AS T
  WHERE F.LineOfAuthoritys = @LineOfAuthority
  AND F.AgentId = @AgentId
  ORDER BY T ASC

请帮帮我!!!

2 个答案:

答案 0 :(得分:1)

样本表

CREATE TABLE #tbLicence (AgentId INT, LineOfAuthority VARCHAR(200), LicenceTypes INT)

INSERT INTO #tbLicence
SELECT    287,  'Bail Bond,Casualty,Dental Services',1
UNION ALL
SELECT     287,  'Casualty,Industrial Fire,Life',4
UNION ALL
SELECT     287,  'Industrial Fire,Life',4

CREATE TABLE #tbLicenceTypes(LicenceTypes INT, LicenceTypesX VARCHAR(200))

INSERT INTO #tbLicenceTypes
SELECT    1,  'Producer'
UNION ALL
SELECT     2,  'Sales Representative'
UNION ALL
SELECT     3,  'Insurance Agent'
UNION ALL
SELECT     4,  'Title Agent'

<强> QUERY

;WITH cte AS 
(
    SELECT 
    AgentId,LicenceTypes,
    CAST('<r>' + REPLACE(REPLACE(LineOfAuthority,'&','&amp;'), ',', '</r>  <r>') + '</r>' AS XML) AS LineOfAuthoritys
    FROM tbLicence
)
,FinalList AS (
    SELECT 
    AgentId,LicenceTypes,
    RTRIM(LTRIM (PTable.PColumn.value('.', 'VARCHAR(MAX)'))) AS LineOfAuthoritys
    FROM cte
    CROSS APPLY LineOfAuthoritys.nodes('//r') AS PTable(PColumn) 
)  
SELECT DISTINCT 
   L.LicenceTypes AS LicenceTypes ,
   L.LicenceTypesX AS LicenceTypesX   
  FROM FinalList F
  JOIN tbLicenceTypes L ON F.LicenceTypes=L.LicenceTypes 
  WHERE F.LineOfAuthoritys = 'Casualty'
  AND F.AgentId = 287
  ORDER BY L.LicenceTypesX ASC

答案 1 :(得分:0)

应使用其他表将LineOfAuthority重新设计为多对多关系。完成后,查询将是一件容易的事。如果你不知道如何建立多对多的关系,你最好先阅读一本关于RDBMS的好书。