簡體   English   中英

SQl:分組依據時計數內的個案

[英]SQl: Case within Count while Group By

我有一個系統,要求用戶填寫一些圖表。 他們可以填寫所需的數量,但至少必須填寫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。

在此處輸入圖片說明

編輯-已添加數據

在此處輸入圖片說明

嘗試這個..

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;

如果我理解正確,您只想將計數限制為最大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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM