通过查询将百分比列添加到简单的t-SQL组

时间:2015-03-23 15:12:31

标签: tsql group-by

我有这个简单的查询

select status,count(*) as [Count] from sms_deliverylog
where dt_log>'2015-03-23' and dt_log <'2015-03-24'
group by status with rollup

给出这个结果

status  Count
ACCEPTD 33
DELIVRD 554
EXPIRED 2
PENDING 72
REJECTD 1
UNDELIV 2
NULL    664
  • 如何根据计数添加简单的百分比列。
  • 如何将上面的NULL重命名为“Total”

由于

修改 请问有一个简单的t-sql替代方案,不涉及使用CTE

1 个答案:

答案 0 :(得分:1)

不会称之为简单,但这是我的尝试:

SELECT
  status,
  count,
  ((CONVERT(DECIMAL, count)/(SELECT COUNT(*) FROM sms_deliverylog WHERE dt_log>'2015-03-23' and dt_log <'2015-03-24'))) * 100 AS '%'
FROM
(
  SELECT
    CASE 
      WHEN status IS NULL THEN 'Total' 
      ELSE status 
    END AS [status],
    COUNT(*) AS [count]
  FROM 
    sms_deliverylog
  WHERE 
    dt_log>'2015-03-23' and dt_log <'2015-03-24'
  GROUP BY STATUS WITH ROLLUP
 ) AS statuscounts

Fiddler Link:http://sqlfiddle.com/#!6/5549f/8/0