2017-02-15 45 views
1

如果我有一個表中的範圍列表,例如SQL將一列數字轉換爲一列中的範圍

ID Number 
1  4 
1  5 
1  6 
1  7 
1  9 

有沒有辦法將這種格式:'4-7,9'放入一個使用SQL的varchar列?

感謝。

+0

你正在使用哪個版本的sql server? –

+0

有沒有其他專欄可以找到訂單? –

+0

請參見[從SQL Server表獲取連續的數字範圍](http://stackoverflow.com/q/33061952/1110897)。 – Serge

回答

1

您可以使用ROW_NUMBERXML PATH

DECLARE @Mock TABLE (Id INT, Number INT) 
INSERT INTO @Mock   
VALUES 
(1, 4), 
(1, 5), 
(1, 6), 
(1, 7), 
(1, 9) 

;WITH CTE 
AS 
(
    SELECT ROW_NUMBER() OVER (ORDER BY Number) AS RowId,* 
    FROM @Mock 
) 

SELECT 
    STUFF(
    (
     SELECT   
      ',' + CAST(MIN(C.Number) AS VARCHAR(10)) + CASE WHEN MIN(C.Number) = MAX(C.Number) THEN '' ELSE '-' + CAST(MAX(C.Number) AS VARCHAR(10)) END 
     FROM 
      CTE C 
     GROUP BY    
      C.Number - C.RowId 
     FOR XML PATH ('') 

    ), 1, 1, '') Result 

輸出:4-7,9

+0

謝謝兩位!這有幫助 – RA19

0

考慮您有另一種尋找範圍的順序

;WITH cte 
    AS (SELECT *, 
       Sum(CASE 
         WHEN number = prev_lag + 1 THEN 0 
         ELSE 1 
        END) 
        OVER(
        ORDER BY iden_col) AS grp 
     FROM (SELECT *, 
         Lag(number) 
          OVER(
          partition BY [ID] 
          ORDER BY iden_col) AS prev_lag 
       FROM Yourtable)a), 
    intr 
    AS (SELECT id, 
       CASE 
        WHEN Min(number) = Max(number) THEN Cast(Min(number) AS VARCHAR(50)) 
        ELSE Concat(Min(number), '-', Max(number)) 
       END AS intr_res 
     FROM cte 
     GROUP BY id, 
        grp) 
SELECT DISTINCT Id, 
       Stuff(concat_col, 1, 1, '') 
FROM intr a 
     CROSS apply (SELECT ',' + intr_res 
        FROM intr b 
        WHERE a.ID = b.ID 
        FOR xml path('')) cs (concat_col) 
相關問題