使用INNER JOIN获取DISTINCT记录

时间:2013-08-07 10:20:44

标签: sql sql-server database sql-server-2008 tsql

我在多表上有以下查询

SELECT DISTINCT b.BoxBarcode as [Box Barcode], (select case when  b.ImagesCount IS NULL
        then 0 
        else  b.ImagesCount end) as [Total Images], s.StageName as [Current   Stage] ,d.DocuementTypeName as [Document Type],
        u.UserName as [Start User],uu.UserName as [Finished User]

FROM [dbo].[Operations] o
    inner join dbo.LKUP_Stages s on 
        o.stageid=s.id
    inner join dbo.LKUP_Users u on
        u.id=o.startuserid
    left join dbo.LKUP_Users uu on
        uu.id=o.FinishedUserID
    inner join boxes b on
        b.id=o.boxid
    inner join LKUP_DocumentTypes d on
        d.ID = b.DocTypeID 

where b.IsExportFinished = 0

当我从Boxes表中选择IsExportFinished = 0时的计数 我得到了42条记录,当我运行上述qoury时,我得到了71条记录, 我只想要Boxes表中的42条记录进行重新审核。

3 个答案:

答案 0 :(得分:4)

您正在进行一对多连接,即至少有一个表具有多个与连接条件匹配的行。

第一步是找出给出“重复”的表格。

完成后,您可以通过向联接添加其他条件来解决问题。我猜测在boxid表中多次出现相同的Operations。如果是这种情况,您需要确定要选择哪个Operation行,然后相应地更新SQL。

答案 1 :(得分:1)

试试这个 -

SELECT
      Box_Barcode = b.BoxBarcode
    , Total_Images = ISNULL(b.ImagesCount, 0)
    , Current_Stage = s.StageName
    , Document_Type = d.DocuementTypeName
    , Start_User = u.UserName
    , Finished_User = uu.UserName
FROM (
    SELECT DISTINCT 
          o.stageid
        , o.boxid
        , o.startuserid
        , o.FinishedUserID
    FROM dbo.[Operations]
) o
JOIN dbo.LKUP_Stages s ON o.stageid = s.id
JOIN dbo.boxes b ON b.id = o.boxid
JOIN dbo.LKUP_DocumentTypes d ON d.id = b.DocTypeID
JOIN dbo.LKUP_Users u ON u.id = o.startuserid
LEFT JOIN dbo.LKUP_Users uu ON uu.id = o.FinishedUserID
WHERE b.IsExportFinished = 0

答案 2 :(得分:0)

我想如果您将LEFT JOIN更改为INNER JOIN,您将获得42条记录。