SQL Server用COUNT计算

时间:2018-08-20 14:39:10

标签: sql sql-server ssms

    select
     category, count(category) as 'TotalCounts',
     COUNT(case kind when 'avail'then 1 else null end) as 'avail',
     Count(case kind when 'offers' then 1 else null end) as 'offers',
     COUNT(CASE contactMethod  WHEN 'SMS' then 1 else null END) as 'SMS',
     COUNT(case contactMethod when 'call' then 1 else null end) as 'call',

     CONVERT(varchar(254),COUNT (case when max_biz_status='A' OR 
     max_biz_status ='B' then 1 else null end) * 100 / count(category)) +'%' 
     as 'Percetange'

     from reports
     group by category
     order by TotalCounts 

我不想像在Convert方法中那样再次计算,而是想像使用我使用TotalCounts一样按顺序使用avail * 100 / TotalCounts。

我尝试过:

 CONVERT(varchar(254),avail * 100 / TotalCounts) +'%' as 'Percetange'

但是我得到了“无效的列名”,以获取有效期和TotalCounts

2 个答案:

答案 0 :(得分:2)

您刚创建它们时不能使用availTotalCounts,因此它们不在范围内,使用公共表表达式是解决此问题的一种方法:

WITH cte AS (
    SELECT
         category, 
         COUNT(category) AS TotalCounts,
         COUNT(case kind WHEN 'avail' THEN 1 ELSE NULL END) AS avail,
         COUNT(case kind WHEN 'offers' THEN 1 ELSE NULL END) AS offers,
         COUNT(CASE contactMethod  WHEN 'SMS' THEN 1 ELSE NULL END) AS SMS,
         COUNT(case contactMethod WHEN 'call' THEN 1 ELSE NULL END) AS [call]
    FROM 
        reports
    GROUP BY 
        category)
SELECT
    *,
    CONVERT(varchar(254),avail * 100 / TotalCounts) +'%' AS Percetange --(sic)
FROM
    cte
ORDER BY 
    TotalCounts;

答案 1 :(得分:2)

您不能这样做,因为您的TotalCounts列是根据结果集创建的。

您可以尝试使用子查询来包含它然后进行计算。

如果您的mssql版本支持CONCAT函数,则可以使用它来使SQL更清晰。

 SELECT t1.*,CONCAT((max_biz_statusCnt * 100 /TotalCounts),'%')as 'Percetange'
 FROM 
 (
    select
     category, 
     count(*) as 'TotalCounts',
     COUNT(case kind when 'avail'then 1 else null end) as 'avail',
     Count(case kind when 'offers' then 1 else null end) as 'offers',
     COUNT(CASE contactMethod  WHEN 'SMS' then 1 else null END) as 'SMS',
     COUNT(case contactMethod when 'call' then 1 else null end) as 'call',
     COUNT (case when max_biz_status='A' OR  max_biz_status ='B' then 1 else null end) 'max_biz_statusCnt'
    from reports
     group by category
 ) t1
 order by TotalCounts