简体   繁体   English

mysql中带有CASE语句的求和

[英]SUM with CASE Statement in mysql

I have following Mysql query 我有以下Mysql查询

SELECT c.`id`
    ,c.`category_name`
    ,c.`category_type`
    ,c.bookmark_count
    ,f.category_id cat_id
    ,f.unfollow_at
    ,(
        CASE WHEN c.id = f.follower_category_id 
               THEN (
                        SELECT count(`user_bookmarks`.`id`)
                        FROM `user_bookmarks`
                        WHERE (`user_bookmarks`.`category_id` = cat_id)
                            AND ((`f`.`unfollow_at` > `user_bookmarks`.`created_at`) || (`f`.`unfollow_at` = '0000-00-00 00:00:00'))
                        ) 
               ELSE 0 END
        ) counter
    ,c.id
    ,f.follower_category_id follow_id
    ,c.user_id
FROM categories c
LEFT JOIN following_follower_categories f ON f.follower_category_id = c.id
WHERE c.user_id = 26
ORDER BY `category_name` ASC

and here is output what i am getting after execuation 这是我执行后得到的输出 见屏幕

now i just want to count . 现在我只想数数。 here i have field id having value 172 against it i have counter 30,3, 2 and Bookmark_count is 4 ( i need to include only once) 在这里,我的字段ID的值为172 ,计数器30,3,2,而Bookmark_count为4 (我只需要包含一次)

and i am accepting output for id 172 is 30+3+2+4(bookmark_count only once) . 我接受ID 172的输出是30 + 3 + 2 + 4(bookmark_count仅一次)

I am not sure how to do this. 我不确定该怎么做。

Can anybody help me out 有人可以帮我吗

Thanks a lot 非常感谢

The following may be the most inefficient query for that purpose, but I added a cover to your query in order to hint at grouping the results. 以下可能是为此目的效率最低的查询,但是我在查询中添加了一个封面,以提示对结果进行分组。 (I removed the second c.id, and my example may have errors since I couldn't try it.) (我删除了第二个c.id,由于无法尝试,我的示例可能有错误。)

SELECT `id`,
       `category_name`,
       `category_type`,
       max(`bookmark_count`),
       `cat_id`,
       `unfollow_at`,
       sum(`counter`)+max(`bookmark_count`) counter,
       follow_id`, `user_id`
FROM
(SELECT c.`id`
    ,c.`category_name`
    ,c.`category_type`
    ,c.bookmark_count
    ,f.category_id cat_id
    ,f.unfollow_at
    ,(
        CASE WHEN c.id = f.follower_category_id
               THEN (
                        SELECT count(`user_bookmarks`.`id`)
                        FROM `user_bookmarks`
                        WHERE (`user_bookmarks`.`category_id` = cat_id)
                            AND ((`f`.`unfollow_at` > `user_bookmarks`.`created_at`) || (`f`.`unfollow_at` = '0000-00-00 00:00:00'))
                        )
               ELSE 0 END
        ) counter
    ,f.follower_category_id follow_id
    ,c.user_id
FROM categories c
LEFT JOIN following_follower_categories f ON f.follower_category_id = c.id
WHERE c.user_id = 26)
GROUP BY `id`, `category_name`, `category_type`, `cat_id`, `unfollow_at`, `follow_id`, `user_id`
ORDER BY `category_name` ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM