count和case when连写
时间: 2023-10-19 07:30:42 浏览: 95
可以使用COUNT函数和CASE WHEN语句连写来进行条件统计。下面是一个示例:
```sql
SELECT
COUNT(CASE WHEN condition THEN 1 END) AS count_condition
FROM
your_table;
```
在上面的示例中,你需要将"condition"替换为你想要应用的条件。COUNT函数会统计满足条件的行数,并将结果存储在名为"count_condition"的列中。你需要将"your_table"替换为实际的表名。
相关问题
修改查询输出为 Q1Count 、Q2Count、Q3Count 和Q4Count 所占 Q1Count +Q2Count+Q3Count +Q4Count 总数的百分比string query1 = "SELECT COUNT(CASE WHEN 季度 = 'Q1' THEN 1 ELSE NULL END) AS Q1Count, COUNT(CASE WHEN 季度 = 'Q2' THEN 1 ELSE NULL END) AS Q2Count,COUNT(CASE WHEN 季度 = 'Q3' THEN 1 ELSE NULL END) AS Q3Count,COUNT(CASE WHEN 季度 = 'Q4' THEN 1 ELSE NULL END) AS Q4Count FROM FAIsum GROUP BY 季度";
可以在查询语句的最后加上以下代码来计算总数和百分比:
```
, COUNT(*) AS TotalCount,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q1' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q1Percent,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q2' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q2Percent,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q3' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q3Percent,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q4' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q4Percent
```
其中,COUNT(*) AS TotalCount 计算总数,SUM(CASE WHEN 季度 = 'Q1' THEN 1 ELSE 0 END) 计算 Q1Count 的总数,其他季度同理。
最后,使用 CONCAT 函数将计算出的百分比与百分号拼接在一起。
修改后的完整查询语句如下:
```
SELECT
COUNT(CASE WHEN 季度 = 'Q1' THEN 1 ELSE NULL END) AS Q1Count,
COUNT(CASE WHEN 季度 = 'Q2' THEN 1 ELSE NULL END) AS Q2Count,
COUNT(CASE WHEN 季度 = 'Q3' THEN 1 ELSE NULL END) AS Q3Count,
COUNT(CASE WHEN 季度 = 'Q4' THEN 1 ELSE NULL END) AS Q4Count,
COUNT(*) AS TotalCount,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q1' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q1Percent,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q2' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q2Percent,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q3' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q3Percent,
CONCAT(ROUND(SUM(CASE WHEN 季度 = 'Q4' THEN 1 ELSE 0 END)/COUNT(*)*100,2), '%') AS Q4Percent
FROM FAIsum
GROUP BY 季度
```
增加查询条件审核年份string query1 = "SELECT 季度,COUNT(CASE WHEN 季度 = 'Q1' THEN 1 ELSE NULL END) AS Q1Count, COUNT(CASE WHEN 季度 = 'Q2' THEN 1 ELSE NULL END) AS Q2Count,COUNT(CASE WHEN 季度 = 'Q3' THEN 1 ELSE NULL END) AS Q3Count,COUNT(CASE WHEN 季度 = 'Q4' THEN 1 ELSE NULL END) AS Q4Count FROM FAIsum GROUP BY 季度";
如果你要在查询语句中增加审核年份的查询条件,可以修改查询语句,添加一个 `WHERE` 子句,例如:
```csharp
string query1 = "SELECT 季度,COUNT(CASE WHEN 季度 = 'Q1' THEN 1 ELSE NULL END) AS Q1Count, COUNT(CASE WHEN 季度 = 'Q2' THEN 1 ELSE NULL END) AS Q2Count,COUNT(CASE WHEN 季度 = 'Q3' THEN 1 ELSE NULL END) AS Q3Count,COUNT(CASE WHEN 季度 = 'Q4' THEN 1 ELSE NULL END) AS Q4Count FROM FAIsum WHERE 审核年份=@value3 GROUP BY 季度";
```
其中,`@value3` 是用来绑定审核年份参数的占位符,你需要在执行查询之前,将其替换成具体的值。例如:
```csharp
adapter.SelectCommand.Parameters.AddWithValue("@value3", dateTimePicker1.Value.Year);
```
其中,`dateTimePicker1.Value.Year` 返回的是 `DateTime` 类型的年份,你需要将其作为参数值添加到查询语句中。
阅读全文