如何改进这个Group by子句

时间:2016-03-08 22:46:55

标签: sql sql-server

我正在尝试使用以下SQL生成报告:

newpage

我的结果如下:

DECLARE @TOTALTRANS int
SET @TOTALTRANS = (SELECT count(*) FROM log_table where answear is not null) 

SELECT  
answear = ISNULL(answear,'Totalization') ,
COUNT(*) as Qtd,
CASE @TOTALTRANS
    WHEN 0 THEN '0%'
    ELSE CONCAT(CAST(((count(*) * 100.0 / @TOTALTRANS)) as decimal(5,2)), ' % ')
END as Porcent
FROM log_table 
WHERE answear is not null
GROUP BY answear WITH ROLLUP 

但我想得到这个结果:

APPROVED 111111 1   0.58 % 
APPROVED 444444 164 95.91 % 
APPROVED 222222 1   0.58 % 
APPROVED 333333 1   0.58 % 
CANCELLED       4   2.34 % 
Totalization  171   100.00 % 

怎么做? 或者甚至改进都是受欢迎的....我也在想也许可以使用union ...

2 个答案:

答案 0 :(得分:1)

理想情况下,您需要将数据规范化以拆分“已批准”和“111111”。如果做不到这一点,这样的事情会让你接近:

DECLARE @TOTALTRANS int
SET @TOTALTRANS = (SELECT count(*) FROM log_table where answear is not null) 

;WITH CleanedUp AS (
  SELECT
    CASE 
      WHEN Answear LIKE 'APPROVED %' THEN 'APPROVED'
      ELSE Answear
    END as Answear
  FROM Log_Table
) 
SELECT
   answear = ISNULL(answear,'Totalization') ,
   COUNT(*) as Qtd,
   CASE @TOTALTRANS
      WHEN 0 THEN '0%'
      ELSE CONCAT(CAST(((count(*) * 100.0 / @TOTALTRANS)) as decimal(5,2)), ' % ')
END as Porcent
FROM CleanedUp
WHERE answear is not null
GROUP BY answear WITH ROLLUP 

答案 1 :(得分:0)

看起来您只需要GROUP BY的第一个空格:

SELECT (CASE WHEN answear IS NULL THEN 'Totalization'
             ELSE LEFT(answear, CHARINDEX(' ', answear) - 1)
        END) as Answear,
       COUNT(*) as Qtd,
       (CASE @TOTALTRANS
          WHEN 0 THEN '0%'
          ELSE CONCAT(CAST(((count(*) * 100.0 / @TOTALTRANS)) as decimal(5,2)), ' % ')
        END) as Porcent
FROM log_table 
WHERE answear is not null
GROUP BY LEFT(answear, CHARINDEX(' ', answear) - 1) WITH ROLLUP ;

此版本假定answear中有空格。