-1

例子:

Code                  T_ID
12345                  1
12345                  2

我想返回以下内容:

 Code             H_T          A_T
 12345             1            2
4

2 回答 2

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
于 2013-10-03T16:39:29.897 回答
1

为了简化答案,了解您是否可以对重复项进行模式/概括会有所帮助。

(1) 您的示例仅显示 1 个重复项。那是代表,还是超过1 dup?如果只有 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 开始,但我们还假设我们只需要报告最多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) 如果您想要无限数量的重复项(因此无法预测的列数),您可能必须进入recursion和/或将您的 SELECT 构建为字符串,使用 EXEC 执行。如果是这样,请说出来,我可以提供更多细节。

希望有帮助,--道格

于 2013-10-03T17:35:30.417 回答