SQl:Count By中的案例

时间:2015-10-19 01:30:37

标签: sql

我有一个系统要求用户填写一些图表。他们可以填写他们想要的数量,但他们必须至少填写2.我需要建立一个SQL调用,计算已填写的表单数量,但每人最多只计算2个。

Count()函数外,一切都按预期工作。

Select mappingid, formTypeId as "Form Type", abbreviation, 
   Count( case when formtypeid >= 2 then 2 else formTypeID end) as "Chart Count"
        From tables.dbo.forms
        where questions = answered and formtypeid = 3
        group by mappingid, formtypeid, abbreviation;

第7行,最后一列应打印出2而不是4。

enter image description here

修改 - 添加数据

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个..

Select mappingid, formTypeId as "Form Type", abbreviation,
case when count(formtypeid) >= 2 then 2 else Count(formTypeID) end as "Chart Count"
From tables.dbo.forms
where questions = answered and formtypeid = 3
group by mappingid, formtypeid, abbreviation;

答案 1 :(得分:1)

如果我理解正确,您只想将计数限制为最多2:

Select mappingid, formTypeId as FormType, abbreviation, 
       (case when count(*) > 2 then 2 else count(*) end) as ChartCount
From tables.dbo.forms
where questions = answered and formtypeid = 3
group by mappingid, formtypeid, abbreviation;