如何获取ID级数据

时间:2014-08-01 20:21:12

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

我有一个名为ID_info的表,示例数据是:

Info_ID   Type  Desc
1         S     Secondary
1         V     Vertical
2         U     Uniform
3         I     Industry
3         F     First

所以我需要一个专栏来告诉我不同​​的ID。计数的第一行应该是数字,后续行应该为null所以我的输出应该是:

   Info_ID   Type  Desc        Count_Info_ID
    1         S     Secondary   2
    1         V     Vertical    NULL
    2         U     Uniform     1
    3         I     Industry    2
    3         F     First       NULL

1 个答案:

答案 0 :(得分:4)

如果订单无关紧要,那么这应该有效:

;WITH CTE AS
(
    SELECT  *, 
            COUNT(*) OVER(PARTITION BY Info_ID) Count_Info_ID, 
            ROW_NUMBER() OVER(PARTITION BY Info_ID ORDER BY Info_ID) RN
    FROM YourTable
)
SELECT  Info_ID,
        [Type],
        [Desc],
        CASE WHEN RN = 1 THEN Count_Info_ID END Count_Info_ID
FROM CTE

Here is demo让你尝试。

结果是:

╔═════════╦══════╦═══════════╦═══════════════╗
║ Info_ID ║ Type ║   Desc    ║ Count_Info_ID ║
╠═════════╬══════╬═══════════╬═══════════════╣
║       1 ║ S    ║ Secondary ║ 2             ║
║       1 ║ V    ║ Vertical  ║ NULL          ║
║       2 ║ U    ║ Uniform   ║ 1             ║
║       3 ║ I    ║ Industry  ║ 2             ║
║       3 ║ F    ║ First     ║ NULL          ║
╚═════════╩══════╩═══════════╩═══════════════╝