如何自我加入一个重复的行显示为一行?

时间:2013-10-03 16:33:50

标签: sql oracle join plsql

示例:

Code                  T_ID
12345                  1
12345                  2

我想返回以下内容:

 Code             H_T          A_T
 12345             1            2

2 个答案:

答案 0 :(得分:1)

我不太确定这里的限制是什么(例如,你有两个以上的代码= 12345的条目吗?),但试试这个大小:

SELECT code, h_t, a_t
FROM   (SELECT    code, MIN(t_id) AS h_t
        FROM      some_table
        GROUP BY  code) mins,
       (SELECT    code, MAX(t_id) AS a_t
        FROM      some_table
        GROUP BY  code) maxs
WHERE  mins.code = maxs.code

答案 1 :(得分:1)

为了简化答案,有助于了解是否存在关于重复项的模式/概括。

(1)您的示例仅显示1个重复。那是代表,还是超过1个重复? 如果只有1个重复,那么最简单的解决方案就是没有JOIN ...只是GROUP BY:

SELECT Code 
   ,H_T = MIN(T_ID)
   ,A_T = MAX(T_ID)
FROM <tableName>  (NOLOCK) 
GROUP BY Code

(2)您的示例显示从1开始的连续自然数。它们始终从1开始吗?它们总是连续的吗?他们能走多远? (任何有效的概括都可以让你简化代码......可能比下面简单。)

例如,如果我们假设重复项不是连续的并且不总是从1开始,但我们还假设我们只需要报告 UP TO 10 重复项, 然后我们可以引入一个ROW_NUMBER(将是连续的并从1开始),然后链接到那个。

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_NAME = 'zz_DupsReport_table1')
    DROP TABLE dbo.zz_DupsReport_table1
SELECT R_NUM = ROW_NUMBER()
            OVER(PARTITION BY Code
                ORDER BY T_ID)
    ,Code
    ,T_ID
INTO dbo.zz_DupsReport_table1
FROM <tableName>  (NOLOCK) 
ORDER BY Code, T_ID

SELECT Code
    ,H_T = T01.T_ID
    ,A_T = T02.T_ID
    ,B_T = T03.T_ID
    ,C_T = T04.T_ID
    ,D_T = T05.T_ID
    ,E_T = T06.T_ID
    ,F_T = T07.T_ID
    ,G_T = T08.T_ID
    ,I_T = T09.T_ID
    ,J_T = T10.T_ID
    ,Over10found = CASE  WHEN Txx.Code IS NULL  THEN 'N'  ELSE 'Y'  END
FROM <tableName>  ORIG (NOLOCK) 
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T01 (NOLOCK)
      ON T01.Code = ORIG.Code  AND T01.R_NUM = 1
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T02 (NOLOCK)
      ON T02.Code = ORIG.Code  AND T02.R_NUM = 2
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T03 (NOLOCK)
      ON T03.Code = ORIG.Code  AND T03.R_NUM = 3
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T04 (NOLOCK)
      ON T04.Code = ORIG.Code  AND T04.R_NUM = 4
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T05 (NOLOCK)
      ON T05.Code = ORIG.Code  AND T05.R_NUM = 5
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T06 (NOLOCK)
      ON T06.Code = ORIG.Code  AND T06.R_NUM = 6
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T07 (NOLOCK)
      ON T07.Code = ORIG.Code  AND T07.R_NUM = 7
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T08 (NOLOCK)
      ON T08.Code = ORIG.Code  AND T08.R_NUM = 8
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T09 (NOLOCK)
      ON T09.Code = ORIG.Code  AND T09.R_NUM = 9
  LEFT OUTER JOIN dbo.zz_DupsReport_table1  T10 (NOLOCK)
      ON T10.Code = ORIG.Code  AND T10.R_NUM = 10
  LEFT OUTER JOIN (SELECT DISTINCT Code  
                   FROM dbo.zz_DupsReport_table1  SUBQ (NOLOCK)
                   WHERE SUBQ.R_NUM > 10
                  ) AS Txx
      ON Txx.Code = ORIG.Code

(3)如果您想要无限数量的重复项(因此需要不可预测的列数),您可能必须进入递归,和/或将SELECT构建为字符串,执行使用EXEC。 如果是这样的话,请说明,我可以提供更多细节。

希望有所帮助, --Doug