连接2个表时重复行

时间:2014-01-28 18:34:54

标签: sql-server-2008

我有一个查询,它读取代码的描述。 两个查询都单独运行,它们返回一行但组合后又会产生一个重复的行。下面是查询

SELECT source, description = IsNull(Max(RTRIM(LTRIM(description))), 'UNKNOWN') 
  FROM SOURCES where source = RTRIM(LTRIM('SCDGIFT12')) 
 GROUP BY source

SELECT UPPER(SOURCECODE) as SOURCECODE,ISNULL(COUNT(ORDER_ID),0) AS ORDID 
  FROM SRC_CODE
 WHERE  CODE = 'SCDGIFT12' AND ORDER_DATE BETWEEN CONVERT(DATETIME,'10/01/2013')     
   AND  CONVERT(DATETIME,'01/26/2014') 
 GROUP BY sourcecode

SELECT SOURCECODE,ORDID,DESCRIPTION 
  FROM ( SELECT UPPER(SOURCECODE) as SOURCECODE, ISNULL(COUNT(ORDER_ID),0) AS ORDID )     
           FROM SRC_CODE  
          WHERE SOURCECODE = 'SCDGIFT12' and ORDER_DATE BETWEEN CONVERT(DATETIME,'10/01/2013') AND CONVERT(DATETIME,'01/26/2014')AND (UPPER(SOURCECODE) IS NOT NULL)  
          GROUP BY  UPPER(SOURCECODE)) AS T LEFT JOIN ( 
                SELECT source, description =  IsNull(Max(RTRIM(LTRIM(description))), 'UNKNOWN') from SOURCES group by source) as B ON  RTRIM(LTRIM(T.SOURCECODE)) = RTRIM(LTRIM(B.SOURCE))  
  ORDER BY sourcecode 

1 个答案:

答案 0 :(得分:0)

我甚至不知道从哪里开始回答这个问题。

  • 您的问题不正确,您没有加入两张桌子。您正在加入两个不同的结果集。
  • 在前2个语句中,您只有两列,但在最后一个语句中,您有3列。
  • 您的代码本身无效,在编译之前需要纠正几个语法错误。你的括号在错误的地方。
  • 我甚至不确定你加入的是什么。
  • 在加入和计数时,你应该把苹果和苹果和橙子放在一起,不要把它们分开计算,然后把它们放在一起,并期望它们都是一样的。

这是您重新格式化的代码,括号移到了正确的位置“我希望”

SELECT SOURCECODE
   ,ORDID
   ,DESCRIPTION
FROM ( SELECT UPPER(SOURCECODE) AS SOURCECODE
           ,ISNULL(COUNT(ORDER_ID), 0) AS ORDID
        FROM SRC_CODE
        WHERE SOURCECODE = 'SCDGIFT12'
            AND ORDER_DATE BETWEEN CONVERT(DATETIME, '10/01/2013')
                           AND     CONVERT(DATETIME, '01/26/2014')
            AND ( UPPER(SOURCECODE) IS NOT NULL )
        GROUP BY UPPER(SOURCECODE) ) AS T
LEFT JOIN ( SELECT source
                   ,description = ISNULL(MAX(RTRIM(LTRIM(description))), 'UNKNOWN')
                FROM SOURCES
                GROUP BY source ) AS B
    ON RTRIM(LTRIM(T.SOURCECODE)) = RTRIM(LTRIM(B.SOURCE))
ORDER BY sourcecode 

我不确定你甚至想要用它来做什么,但如果你想要的是摆脱重复,你可以放DISTINCT来消除重复的行,但这并不能解决你的根本问题。你需要弄清楚你想要计算的是什么,并想出更好的方法将它放在一起而不是加入子查询。