2010-04-23 107 views
0
這樣

項目進行排序算

d B C

我有數據

一個d

C B

A B

下的

下的d

Ç

如果分析,就會發現每個元素的外觀如下

一個:4 B:3- C:5 d:2

根據外觀我的已排序的元件將是 C,A,b,d

和最終輸出應是

CBD

一個d

C B

A B

下的

下的d

Ç

任何線索,我們如何才能做到這一點使用SQL查詢?

+0

這些是三個不同的列還是一列? – 2010-04-23 06:03:41

+0

這些是不同的列 – 2010-04-23 06:04:13

+0

在你的數據中顯示的列是否代表列?如果是這樣,他們爲什麼被重新訂購? – TerrorAustralis 2010-04-23 06:20:15

回答

0

除非是規定了輸入行的順序另一列,就不可能保證輸出行以相同的順序返回。我在這裏做了一個假設,以三列值對它們進行排序,以便結果是確定性的。

將代碼壓縮成更少的步驟是可能的,但可以合理清晰地顯示步驟。

注意,對於大型數據集,它可能是更有效地劃分某些步驟爲SELECT INTO操作創建臨時表或工作表。

DECLARE @t TABLE 
(col1 CHAR(1) 
,col2 CHAR(1) 
,col3 CHAR(1) 
) 

INSERT @t 
     SELECT 'd','b','c' 
UNION SELECT 'a','d',NULL 
UNION SELECT 'c','b',NULL 
UNION SELECT 'a','b',NULL 
UNION SELECT 'c','a',NULL 
UNION SELECT 'c','a','d' 
UNION SELECT 'c',NULL,NULL 


;WITH freqCTE 
AS 
(
     SELECT col1 FROM @t WHERE col1 IS NOT NULL 

     UNION ALL 

     SELECT col2 FROM @t WHERE col2 IS NOT NULL 

     UNION ALL 

     SELECT col3 FROM @t WHERE col3 IS NOT NULL   
) 
,grpCTE 
AS 
(
     SELECT col1 AS val 
       ,COUNT(1) AS cnt 
     FROM freqCTE 
     GROUP BY col1 

) 
,rowNCTE 
AS 
(
       SELECT * 
         ,ROW_NUMBER() OVER (ORDER BY col1 
                ,col2 
                ,col3 
              ) AS rowN 
       FROM @t 
) 
,buildCTE 
AS 
(
     SELECT rowN 
       ,val 
       ,cnt 
       ,ROW_NUMBER() OVER (PARTITION BY rowN 
            ORDER BY  ISNULL(cnt,-1) DESC 
               ,ISNULL(val,'z') 
            ) AS colOrd 
     FROM (       
       SELECT * 
       FROM   rowNCTE AS t 
       JOIN   grpCTE AS g1 
       ON    g1.val = t.col1 

       UNION ALL 

       SELECT * 
       FROM   rowNCTE AS t 
       LEFT JOIN  grpCTE AS g2 
       ON    g2.val = t.col2 

       UNION ALL 

       SELECT * 
       FROM   rowNCTE AS t 
       LEFT JOIN  grpCTE AS g3 
       ON    g3.val = t.col3 
      ) AS x 
) 
SELECT b1.val AS col1 
     ,b2.val AS col2 
     ,b3.val AS col3 
FROM buildCTE AS b1 
JOIN buildCTE AS b2 
ON b2.rowN = b1.rowN 
AND b2.colOrd = 2 
JOIN buildCTE AS b3 
ON b3.rowN = b1.rowN 
AND b3.colOrd = 3 
WHERE b1.colOrd = 1 
ORDER BY b1.rowN 
+0

此查詢給出了10分0R多個列 – 2010-04-26 11:02:49

+0

@Anil鬃毛內存不足的異常錯誤 - 在什麼環境? – 2010-04-26 20:23:36

+0

@Anil Mane - 你有沒有試過我的建議,選擇一些臨時表的步驟? – 2010-04-27 15:01:44

相關問題