You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL如何统计行中包含指定值的列数?

Solution to Count 'A' Values per ID in MySQL

To solve this problem, we can calculate the number of 'A's for each row by checking each column individually and summing up the matches. Here's a straightforward approach:

MySQL Query

SELECT 
    ID,
    (day1 = 'A') + (day2 = 'A') + (day3 = 'A') + (day4 = 'A') AS Count
FROM xyz;

How It Works

  • In MySQL, boolean conditions like day1 = 'A' return 1 when true and 0 when false. Adding these values together gives the total number of columns containing 'A' for each row.
  • We use the alias Count to match your expected output format.

Expected Result

Running this query will return exactly the result you're looking for:

ID Count
1  2
2  3
3  4
4  1

Alternative Explicit Version (Using CASE Statements)

If you prefer more explicit logic (useful if you need to handle NULLs or complex conditions later), you can use CASE statements instead:

SELECT 
    ID,
    CASE WHEN day1 = 'A' THEN 1 ELSE 0 END +
    CASE WHEN day2 = 'A' THEN 1 ELSE 0 END +
    CASE WHEN day3 = 'A' THEN 1 ELSE 0 END +
    CASE WHEN day4 = 'A' THEN 1 ELSE 0 END AS Count
FROM xyz;

Both queries produce identical results—choose whichever fits your readability preference.

内容的提问来源于stack exchange,提问作者karan sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:17:48