我有这个SQL请求但不起作用......我真的不知道为什么因为我开始使用SQL ...
Select CDR.*,
p1.*,
p2.*,
p3.*
From dbo.T_CDR_APPEL CDR
Inner Join dbo.POS As p1 On CDR.CDR_LOC_CODE = p1.Loc_Code And
CDR.CDR_LOC_CODE Like 'SC%VI%' And CDR.CDR_TYPE Like 'I%'
Inner Join dbo.POS As p2 On CDR.CDR_LAST_REDIR_NO = p2.Post_type And
CDR.CDR_LOC_CODE Like 'CCN%' And CDR.CDR_TYPE Like 'I'
Inner Join dbo.POS As p3 On CDR.CDR_LAST_REDIR_NO = p3.Backup_Number And
CDR.CDR_LOC_CODE Like 'VoiceMail%' And CDR.CDR_TYPE Like 'IF'
感谢您的帮助
答案 0 :(得分:2)
您的选择陈述
Select CDR.*,
p1.*,
p2.*,
p3.*
From dbo.T_CDR_APPEL CDR
Inner Join dbo.POS As p1 On CDR.CDR_LOC_CODE = p1.Loc_Code And
CDR.CDR_LOC_CODE Like 'SC%VI%' And CDR.CDR_TYPE Like 'I%'
Inner Join dbo.POS As p2 On CDR.CDR_LAST_REDIR_NO = p2.Post_type And
CDR.CDR_LOC_CODE Like 'CCN%' And CDR.CDR_TYPE Like 'I'
Inner Join dbo.POS As p3 On CDR.CDR_LAST_REDIR_NO = p3.Backup_Number And
CDR.CDR_LOC_CODE Like 'VoiceMail%' And CDR.CDR_TYPE Like 'IF'
与
基本相同SELECT CDR.*,
p1.*,
p2.*,
p3.*
FROM dbo.T_CDR_APPEL CDR
INNER JOIN dbo.POS AS p1 ON CDR.CDR_LOC_CODE = p1.Loc_Code
INNER JOIN dbo.POS AS p2 ON CDR.CDR_LAST_REDIR_NO = p2.Post_type
INNER JOIN dbo.POS AS p3 ON CDR.CDR_LAST_REDIR_NO = p3.Backup_Number
WHERE
CDR.CDR_LOC_CODE LIKE 'SC%VI%' AND
CDR.CDR_LOC_CODE LIKE 'CCN%' AND
CDR.CDR_LOC_CODE LIKE 'VoiceMail%' AND
CDR.CDR_TYPE LIKE 'I%' AND
CDR.CDR_TYPE LIKE 'I' AND
CDR.CDR_TYPE LIKE 'IF'
因此,问题是WHERE
子句,AND
条件的多个组合CDR.CDR_LOC_CODE
和CDR.CDR_TYPE
。请尝试将AND
替换为OR
。
<强>更新强>:
由于p1,p2,p3
属于同一个表,因此要避免重复列,请尝试使用
SELECT CDR.*, p.* FROM
(
SELECT *,
(CASE
WHEN CDR_TYPE LIKE 'I%' THEN CDR_LOC_CODE
WHEN CDR_TYPE LIKE 'I' THEN CDR_LAST_REDIR_NO
WHEN CDR_TYPE LIKE 'IF' THEN CDR_LAST_REDIR_NO
ELSE ''
END) TMP_COL FROM dbo.T_CDR_APPEL
) CDR
INNER JOIN dbo.POS p ON
(CASE
WHEN CDR.CDR_TYPE LIKE 'I%' THEN p.Loc_Code
WHEN CDR.CDR_TYPE LIKE 'I' THEN p.Post_type
WHEN CDR.CDR_TYPE LIKE 'IF' THEN p.Backup_Number
ELSE ''
END) = CDR.TMP_COL
WHERE
(CDR.CDR_LOC_CODE LIKE 'SC%VI%' AND CDR.CDR_TYPE LIKE 'I%') OR
(CDR.CDR_LOC_CODE LIKE 'CCN%' AND CDR.CDR_TYPE LIKE 'I') OR
(CDR.CDR_LOC_CODE LIKE 'VoiceMail%' AND CDR.CDR_TYPE LIKE 'IF')
注意:运行上面的查询可能需要一段时间才能使用大表。您可能希望在WHERE
子句中添加一些条件以进一步调整。此外,我们应该将WHERE
子句放到子查询中,因为CDR_LOC_CODE
和CDR_TYPE
属于同一个表dbo.T_CDR_APPEL
。同时为动态列TMP_COL
选中Null或为空,以避免加入表ON '' = ''
或ON NULL = NULL
。
SELECT CDR.*, p.* FROM
(
SELECT *,
(CASE
WHEN CDR_TYPE LIKE 'I%' THEN CDR_LOC_CODE
WHEN CDR_TYPE LIKE 'I' THEN CDR_LAST_REDIR_NO
WHEN CDR_TYPE LIKE 'IF' THEN CDR_LAST_REDIR_NO
ELSE ''
END) TMP_COL FROM dbo.T_CDR_APPEL
WHERE
(CDR_LOC_CODE LIKE 'SC%VI%' AND CDR_TYPE LIKE 'I%') OR
(CDR_LOC_CODE LIKE 'CCN%' AND CDR_TYPE LIKE 'I') OR
(CDR_LOC_CODE LIKE 'VoiceMail%' AND CDR_TYPE LIKE 'IF')
) CDR
INNER JOIN dbo.POS p ON
(CASE
WHEN CDR.CDR_TYPE LIKE 'I%' THEN p.Loc_Code
WHEN CDR.CDR_TYPE LIKE 'I' THEN p.Post_type
WHEN CDR.CDR_TYPE LIKE 'IF' THEN p.Backup_Number
ELSE ''
END) = CDR.TMP_COL AND NULLIF(CDR.TMP_COL, '') IS NOT NULL