如何进行分组?

时间:2013-05-17 10:16:10

标签: sql sql-server-2008

我有一张

下的表格

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

我需要做些什么改变才能获得理想的结果?

1 个答案:

答案 0 :(得分:3)

您已经完成了所有艰苦的工作,实际上,您只需要处理ROLLUP中的各种SELECT行。

这对我来说非常好:

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