在两个MySQL字段上使用COUNT(然后需要两个字段的总和)

时间:2017-03-30 15:36:13

标签: mysql

我有以下MySQL查询可以正常工作,给我“smconnectivity_b”字段的计数。

我们添加了第二个字段:“smconnectivity_c”,它也可以有值。

我需要在下面的相同Count逻辑中包含这些新值中的任何一个:

    SELECT smconnectivity_b, COUNT(smconnectivity_b) AS Used, LEFT(smconnectivity_b, 4) AS Collo, 144 - COUNT(smconnectivity_b) AS Available, concat(round(( COUNT(smconnectivity_b)/144 * 100 ),1),'%') AS percentage, (round(( COUNT(smconnectivity_b)/144 * 100 ),1)) AS percentage2,

CASE 
        WHEN COUNT(smconnectivity_b) >= 25 AND COUNT(smconnectivity_b) < 121 THEN 'Yellow'
        WHEN COUNT(smconnectivity_b) >= 121 AND COUNT(smconnectivity_b) < 145 THEN 'Red'

ELSE 'Green'
END AS Color

FROM     tblsplicemapping

GROUP BY smconnectivity_b
ORDER BY smconnectivity_b

2 个答案:

答案 0 :(得分:1)

首先,您的查询可能会更快:

SELECT  smconnectivity_b, Used, 
        LEFT(smconnectivity_b, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage, 
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE 
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_b, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_b
    ) subselect
ORDER BY smconnectivity_b

现在...

  

我们添加了第二个字段:&#34; smconnectivity_c&#34;也可以有价值。我需要在下面的相同计数逻辑中包含任何这些新值

在此查询中,您无法真正做到这一点。最简单的方法是进行两次单独的查询。如果要组合它们,可以始终使用UNION ALL。

答案 1 :(得分:0)

感谢@peufeu我更新了查询&amp;使用UNION ALL组合两个字段计数。感谢。

以下是最终更新的查询:

(SELECT  smconnectivity_b, Used, 
        LEFT(smconnectivity_b, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage, 
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE 
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_b, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_b
    ) subselect
)

UNION ALL

(SELECT  smconnectivity_c AS smconnectivity_b, Used, 
        LEFT(smconnectivity_c, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage, 
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE 
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_c, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_c
    ) subselect
)
ORDER BY smconnectivity_b