MYSQL查询总数不正确

时间:2019-10-07 09:48:23

标签: mysql sql

我正在进行查询,以获取所有公司的所有不同尺寸类型。
我的查询如下:

SELECT
  (
    SELECT COUNT(*) 
    FROM companies 
    WHERE CONCAT(Allin + Basis + Entry + 3CXusers) > 4 
    AND CONCAT(Allin + Basis + Entry + 3CXusers) < 11 
    AND YEAR = 2018 AND Period = 12 
  ) AS mini,
  (
    SELECT COUNT(*) 
    FROM companies 
    WHERE CONCAT(Allin + Basis + Entry + 3CXusers) > 9 
    AND CONCAT(Allin + Basis + Entry + 3CXusers) < 51 
    AND YEAR = 2018 AND Period = 12 
  ) AS small,
  (
    SELECT COUNT(*) 
    FROM companies 
    WHERE CONCAT(Allin + Basis + Entry + 3CXusers) > 49 
    AND CONCAT(Allin + Basis + Entry + 3CXusers) < 251 
    AND YEAR = 2018 AND Period = 12 
  ) AS medium,
  (
    SELECT COUNT(*) 
    FROM companies 
    WHERE CONCAT(Allin + Basis + Entry + 3CXusers) > 249
    AND YEAR = 2018 AND Period = 12 
  ) AS large,
  (
    SELECT COUNT(*) 
    FROM companies 
    WHERE CONCAT(Allin + Basis + Entry + 3CXusers) > 4 
    AND YEAR = 2018 AND Period = 12 
  ) AS total
FROM companies 
LIMIT 1

我得到的结果是:

| mini | small | medium | large | total | 
|  133 |  224  |   58   |   5   |  400  |

有人可以解释为什么我得到400而不是420的原因吗?
如您所见,我选择了所有规模大于4的公司。
我选择的所有尺寸的尺码都超过4,但是为什么我总共得到400?

这真的很奇怪。

我的SQL结构如下:

| company_id | Year | Period | Allin | Basis | Entry | 3CXusers |  
| 999        | 2018 | 12     | 34    | 56    | 12    | 0        | // example row

我希望得到以下结果:

| mini | small | medium | large | total | 
|  133 |  224  |   58   |   5   |  420  |

2 个答案:

答案 0 :(得分:2)

当检查尺寸限制时,您会发现有重叠。例如,在第一个中,您有4

答案 1 :(得分:1)

结合以上建议的评论/答案:

WITH cte(MyVal) AS (
  SELECT CONCAT(Allin + Basis + Entry + 3CXusers) AS MyVal
  FROM companies
)
SELECT
  SUM(CASE WHEN MyVal > 4 AND MyVal < 11 THEN 1 ELSE 0 END) AS mini,
  SUM(CASE WHEN MyVal > 9 AND MyVal < 51 THEN 1 ELSE 0 END) AS small,
  SUM(CASE WHEN MyVal > 49 AND MyVal < 251 THEN 1 ELSE 0 END) AS medium,
  SUM(CASE WHEN MyVal > 249 THEN 1 ELSE 0 END) AS large,
  SUM(CASE WHEN MyVal > 4 THEN 1 ELSE 0 END) AS total -- Must come after "mini" check
FROM cte
WHERE YEAR = 2018 
AND Period = 12 

通过这种方式查看范围重叠会更容易一些。使用BETWEEN会更干净,但这是包含在内的,并且您的查询范围是排除的。