很抱歉标题混乱,不知道怎么说这个。
我有一个事件表,以及这些事件的赌注表。我已经获取了每个赛事的总金额,但我也想获取赔率(也就是说,一支球队的总数除以另一支球队的总数)。下注的参与者存储在horse
表的data_bets
列中。
例如,我想添加类似的内容:
SELECT
SUM(data_bets.amount) WHERE data_bets.horse = data_events.challenger
/
SUM(data_bets.amount) WHERE data_bets.horse = data_events.contestant
AS bet_odds
到我现有的查询:
SELECT *,
SUM(data_bets.amount) AS total_pot,
COUNT(data_bets.member) AS total_bets,
COUNT(data_votes.member) AS total_votes,
data_platforms.name AS platform_name, data_platforms.icon AS platform_icon
FROM data_events
LEFT JOIN data_bets ON data_bets.event=data_events.id
LEFT JOIN data_votes ON data_votes.content_type=2 AND data_votes.content_id=data_events.id
LEFT JOIN data_platforms ON data_platforms.id=data_events.platform
WHERE status=1
GROUP BY data_events.id
ORDER BY total_pot DESC
这可以用一个查询吗?如果可能,我更愿意同时取challenger_odds
和contestant_odds
:
SELECT
SUM(data_bets.amount) WHERE data_bets.horse = data_events.challenger
/
SUM(data_bets.amount) WHERE data_bets.horse = data_events.contestant
AS challenger_odds,
SUM(data_bets.amount) WHERE data_bets.horse = data_events.contestant
/
SUM(data_bets.amount) WHERE data_bets.horse = data_events.challenger
AS contestant_odds
答案 0 :(得分:1)
使用条件聚合:
SELECT (SUM(CASE WHEN data_bets.horse = data_events.challenger THEN data_bets.amount ELSE 0 END) /
SUM(CASE WHEN data_bets.horse = data_events.contestant THEN data_bets.amount END)
) as bet_odds