2011-03-30

MS-SQL:將資料分組並比較資料大小

通常,我們將資料分組並且比較大小(如圖一整理成圖二),可以結合ORDER BY、GROUP BY,一個語法簡單搞定。如下所示:

                                               《圖一.資料原始檔》


原始資料如下:
    select title,val,note from data_compare

分組並按大→小排列:
    SELECT title,val,note FROM data_compare
    ORDER BY title, val desc

                                               《圖二.整理後資料》

但如果是需要用其它文字代替比較出來的結果(如圖三所示),那可能有點麻煩…


                                             《圖三.用其它文字代替比較出來的結果》

使用cursor一筆一筆處理解決似乎是不錯的辦法,但考慮到日後資料量變得龐大及其轉檔效能,這就變成最後的手段了。
在此提供另一種方式:
構想:
    1.先將各組最大值及最小值分別取出放入暫存table#A、#B
    2.排除最大值及最小值取出剩餘資料,即為中間值
    3.將要替代的文字一一放入最大值、最小值、中間值資料表,UNION ALL,完成!
程式碼如下:

SELECT distinct title, maxval=MAX(val)
into #A
FROM data_compare
GROUP BY title

SELECT distinct title, minval=MIN(val)
into #B
FROM data_compare
GROUP BY title

SELECT distinct data_compare.title, '棒' as val, data_compare.note
FROM data_compare
JOIN #A ON data_compare.title=#A.title
JOIN #B ON data_compare.title=#B.title
WHERE data_compare.val=#A.maxval and data_compare.title=#A.title
UNION ALL
SELECT distinct data_compare.title, '不錯' as val, data_compare.note
FROM data_compare
JOIN #A ON data_compare.title=#A.title
JOIN #B ON data_compare.title=#B.title
WHERE (data_compare.val<>#A.maxval and data_compare.title=#A.title) and (data_compare.val<>#B.minval and data_compare.title=#B.title)
UNION ALL
SELECT distinct data_compare.title, '加油' as val, data_compare.note
FROM data_compare
JOIN #A ON data_compare.title=#A.title
JOIN #B ON data_compare.title=#B.title
WHERE data_compare.val=#B.minval and data_compare.title=#B.title

沒有留言:

張貼留言