如何使用案例陈述最好计算(*)?

时间:2016-12-13 23:21:29

标签: sql sql-server case

以下SQL(在SQL Server上)返回错误:

  

'*'

附近的语法不正确

使用以下SELECT语句是否存在固有的错误?:

SELECT
COUNT(CASE WHEN <conditions> THEN * ELSE NULL END) as conditionalcountall
FROM TABLE

我尝试了这种变化也失败了:

SELECT
CASE WHEN <conditions> THEN COUNT(*) ELSE NULL END as conditionalcountall
FROM TABLE

4 个答案:

答案 0 :(得分:5)

我倾向于喜欢sum()

SELECT
SUM(CASE WHEN <conditions> THEN 1 ELSE 0 END) as conditionalcountall
FROM TABLE

答案 1 :(得分:2)

试试这个,它是经过测试的

SELECT
CASE WHEN 1 = 1 THEN COUNT(*) ELSE NULL END as conditionalcountall
FROM TABLE

1 = 1是示例条件

<强>演示: -

Create table #temp (id int , col1 varchar (10))
go

insert into #temp values (1 , 'aaaa')
insert into #temp values (2 , 'bbbb')
insert into #temp values (3 , 'cccc')

SELECT
CASE WHEN 1 = 1 THEN COUNT(*) ELSE NULL END as conditionalcountall
FROM #temp

<强>结果:

enter image description here

id = 1之类的案例中,您应该在select Count(*) CASE查询中SELECT CASE WHEN id = 1 THEN (select COUNT(*) from #temp) ELSE NULL END as conditionalcountall FROM #temp

像这样:

Count(*)

<强>结果: -

enter image description here

注意:如果您直接使用group by,则计算了id列,因此您应该使用SELECT CASE WHEN id = 1 THEN COUNT(*) ELSE NULL END as conditionalcountall FROM #temp group by id 作为下一个:

re.finditer

<强>结果:

enter image description here

答案 2 :(得分:0)

SELECT
   CASE WHEN X THEN Y
   ELSE Z
   END *NEW COLUMN NAME*
,  COUNT(*)
FROM 
   TABLE
GROUP BY
   *NEW COLUMN NAME*

这应该返回两列,一列是buckets/case语句,另一列是每个bucket的列数

这个方法对我来说是最直接的

答案 3 :(得分:-1)

如果您真的想要使用COUNT,那么您可以这样做:

SELECT 
    COUNT(*)
FROM table
WHERE <conditions>