SUM大小写返回没有GROUP BY的值

时间:2015-06-16 12:54:15

标签: mysql sql group-by sum case

当我在我的case select周围添加SUM时,它返回没有GROUP BY的求和值。

我使用的查询,没有SUM,是以下

SELECT CASE WHEN subscription_types.type  = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used
INNER JOIN training_sessions ON  training_sessions.id = subscription_used.training_session_id
INNER JOIN training_series AS tserie ON tserie.id = training_sessions.training_serie_id
INNER JOIN user_training_session ON user_training_session.training_session_id = training_sessions.id
INNER JOIN subscriptions ON subscriptions.id = subscription_used.subscription_id
INNER JOIN subscription_types ON subscription_types.id = subscriptions.subscription_type_id
WHERE subscription_used.training_session_id =  (SELECT training_sessions.id FROM training_sessions WHERE DATE(event_start_date) = @week_2_ago_date AND training_serie_id = 17) AND present=1
GROUP BY subscriptions.id

此查询返回值:8,7。但是,当我在案例中放置一个SUM时,它给出了数字75. 75是没有GROUP BY返回的值的和。

有关如何解决此问题的任何想法,以便查询给我正确的值(8 + 7 = 15,1行)?提前致谢

1 个答案:

答案 0 :(得分:0)

Group by暗示基于subscription.id的不同值,所以如果你带着这个小组,你可能会得到像8,8,8,8,8,7,7,7,7这样的东西,因为加入等等。

使用该组时,您只能获得8和7的不同值。当您对该组求和时,它将对所有这些值求和,但不是2个不同。

最简单的解决方案,将为您提供15:

SELECT SUM(SUBSCRIPTION_USED) FROM (
SELECT CASE WHEN subscription_types.type  = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used
INNER JOIN training_sessions ON  training_sessions.id = subscription_used.training_session_id
INNER JOIN training_series AS tserie ON tserie.id = training_sessions.training_serie_id
INNER JOIN user_training_session ON user_training_session.training_session_id = training_sessions.id
INNER JOIN subscriptions ON subscriptions.id = subscription_used.subscription_id
INNER JOIN subscription_types ON subscription_types.id = subscriptions.subscription_type_id
WHERE subscription_used.training_session_id =  (SELECT training_sessions.id FROM training_sessions WHERE DATE(event_start_date) = @week_2_ago_date AND training_serie_id = 17) AND present=1
GROUP BY subscriptions.id);

虽然可能是更好的方式来编写它。

编辑:如果你只想对不同的值求和,你也可以做SUM(DISTINCT CASE ......)。