INNER JOIN查询一侧可以为空的位置

时间:2019-05-16 06:05:26

标签: sql sql-server join isnull

我有一个动态查询,如下所示,但是T.tmpPointsMale或T.tmpPointsFemale可以为NULL或0,因此当我需要它时,记录就不会出现在结果中。

我认为不建议使用apply(),我看到了有关使用UNION的建议,但不确定如何在此查询中实现。

ISNULL

对不起,我无法发布图片(我将示例数据放入电子表格中以粘贴在此处,但它作为图片出现)

tblCompetitors

tblTempPointsHistoryReport

Expected Result

我加载此代码调用的数据表

@CplsNo int,
@Overide int,
@CoupleNum int NULL
    AS
    BEGIN
SET NOCOUNT ON;
DECLARE @SQL NVARCHAR(2000), @Where NVARCHAR(1000)

SET @SQL = 'SELECT T.tmpPointsMale, T.tmpPointsFemale, MAX(ISNULL(M.First_Name,'''') +'' ''+ ISNULL(M.Surname,'''')) AS Male, MAX(ISNULL(F.First_Name,'''') +'' ''+ ISNULL(F.Surname,'''')) AS Female, MAX(ISNULL(M.eMail_Address,'''')) as Adr1, MAX(ISNULL(F.eMail_Address,'''')) as Adr2, MAX(CONVERT(INT,M.Contactable)) As Mcontact, MAX(CONVERT(INT,F.Contactable)) As Fcontact
    FROM tblTempPointsHistoryReport T

    INNER JOIN tblCouples C ON C.MaleID = T.tmpPointsMale or C.FemaleID = T.tmpPointsFemale
    INNER JOIN tblCompetitors M ON M.Competitor_Idx = T.tmpPointsMale
    INNER JOIN tblCompetitors F ON F.Competitor_Idx = T.tmpPointsFemale '

    IF @Overide = 0
        BEGIN
            SET @Where = 
            'WHERE C.YearCpl = YEAR(CURRENT_TIMESTAMP) And Len(LTRIM(RTRIM(M.eMail_Address))) + Len(LTRIM(RTRIM(F.eMail_Address))) > 0 '
                IF @CplsNo = 1
                    SET @Where = @Where + 
                    'And C.CoupleNumber = @CoupleNum '
        END

    IF @Overide = 1
        BEGIN
            SET @Where =
            'WHERE Len(LTRIM(RTRIM(M.eMail_Address))) + Len(LTRIM(RTRIM(F.eMail_Address))) > 0 '
                IF @CplsNo = 1
                SET @Where = @Where + 
                'And C.CoupleNumber = @CoupleNum '
        END

    BEGIN 
    SET @SQL = @SQL + @Where + 'GROUP BY T.tmpPointsMale, T.tmpPointsFemale'

      EXEC sp_executesql @SQL,N'@CplsNo int,@Overide int,@CoupleNum int',@CplsNo, @Overide, @CoupleNum

0 个答案:

没有答案