2013-05-17 41 views
4

我有一個表作爲下如何分組?

enter image description here

我所要的輸出是作爲

enter image description here

我火了下面的查詢

;WITH CTE AS 
(
    Select script_Type = 'SP',detail_warnings ='Consider using EXISTS predicate instead of IN predicate' UNION ALL 
    Select script_Type = 'SP',detail_warnings ='ExcludeItem does not exist in database SQLEye or is invalid for this operation' UNION ALL 
    Select script_Type='SP',detail_warnings ='Values hardcoded in where-clause condition' UNION ALL 
    Select script_Type='Table',detail_warnings ='Table name is not singular Remarks :1:- Missing create index statement.' UNION ALL 
    Select script_Type='Table',detail_warnings ='Check for existence object then Drop statement before create statement' UNION ALL 
    Select script_Type='View',detail_warnings ='Invalid name' 
) 

SELECT script_Type,detail_warnings,COUNT(script_Type) 
FROM CTE c WITH(NOLOCK) 
GROUP BY ROLLUP(script_Type,detail_warnings) 

但輸出爲在

enter image description here

我需要做些什麼才能獲得理想的結果?

回答

3

你已經在這裏完成了所有的辛苦工作,實際上,你只需要處理SELECT中的各種ROLLUP行。

這看起來相當不錯,我:

WITH CTE AS 
(
    Select script_Type = 'SP',detail_warnings ='Consider using EXISTS predicate instead of IN predicate' UNION ALL 
    Select script_Type = 'SP',detail_warnings ='ExcludeItem does not exist in database SQLEye or is invalid for this operation' UNION ALL 
    Select script_Type='SP',detail_warnings ='Values hardcoded in where-clause condition' UNION ALL 
    Select script_Type='Table',detail_warnings ='Table name is not singular Remarks :1:- Missing create index statement.' UNION ALL 
    Select script_Type='Table',detail_warnings ='Check for existence object then Drop statement before create statement' UNION ALL 
    Select script_Type='View',detail_warnings ='Invalid name' 
) 

SELECT script_Type = case 
    when script_Type is null and detail_warnings is null then 'Total' 
    when detail_warnings is null then script_Type + ' Count' 
    else script_Type end 
    ,detail_warnings = isnull(detail_warnings, '') 
    ,COUNT(script_Type) 
FROM CTE c WITH(NOLOCK) 
GROUP BY ROLLUP(script_Type,detail_warnings) 

SQL Fiddle with demo