针对同一表格针对不同条件获取不同的计数

时间:2018-02-08 03:52:17

标签: mysql database count

我已经检查并尝试了这个solution,但这对我不起作用。简单的查询是

  [[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.1    5    9 13.0 17.0
[2,]  2.0    6   10  1.4 18.0
[3,]  3.0    7   11 15.0  1.1
[4,]  4.0    8   12 16.0 20.0

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    5    9   13   17
[2,]    2    6   10   28   18
[3,]    3    7   11   15   38
[4,]    4    8   12   16   20

[[3]]
[,1] [,2] [,3] [,4] [,5]
[1,]  100    5    9   13   17
[2,]    2    6   10 1400   18
[3,]    3    7   11   15 1900
[4,]    4    8   12   16   20

输出

enter image description here

在上面的结果中,SELECT COUNT(ims.`installation_id`) AS 'total_images', COUNT(ims.`image_name`) AS 'images_uploaded' FROM `installation_images_site` ims INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id` WHERE ims.`installation_id` = 1 AND ims.`image_upload_flag` = 1 为2但实际上是4. total_images的输出是正确的。但我希望得到不同的结果。以下是我的尝试

images_uploaded

我现在得到的输出是

enter image description here

计数没问题,但我想要两个单独的列SELECT COUNT(ims.`installation_id`) AS 'total_images' FROM `installation_images_site` ims INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id` WHERE ims.`installation_id` = 1 GROUP BY ims.`installation_id` UNION ALL SELECT COUNT(ims.`id`) AS 'images_uploaded' FROM `installation_images_site` ims INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id` WHERE ims.`image_upload_flag` = 1 AND ims.`installation_id` = 1 total_images

我怎样才能实现这一目标?任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

您实际上可以使用条件聚合函数

来简化查询
SELECT  SUM(CASE WHEN ims.`installation_id` = 1 THEN 1 ELSE 0 END) AS total_images, 
        SUM(CASE WHEN ims.`image_upload_flag` = 1 AND ims.`installation_id` = 1 THEN 1 ELSE 0 END) AS images_uploaded
FROM    `installation_images_site` ims
        INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id`
WHERE   (ims.`image_upload_flag` = 1 AND ims.`installation_id` = 1)
        OR (ims.`installation_id` = 1) 
GROUP   BY ims.`installation_id`

或将查询包装在子查询中,该子查询提供相同的结果

SELECT  MAX(CASE WHEN RN = 1 THEN total_count ELSE 0 END) AS total_images,
        MAX(CASE WHEN RN = 2 THEN total_count ELSE 0 END) AS images_uploaded
FROM
    (
        SELECT COUNT(ims.`installation_id`) AS 'total_count', 1 AS RN
        FROM `installation_images_site` ims
        INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id`
        WHERE ims.`installation_id` = 1 
        GROUP BY ims.`installation_id`
        UNION ALL
        SELECT COUNT(ims.`id`) AS 'total_count', 2 AS RN
        FROM `installation_images_site` ims
        INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id`
        WHERE ims.`image_upload_flag` = 1 AND ims.`installation_id` = 1
    ) a
相关问题