将聚合放入组中

时间:2015-02-15 22:12:30

标签: sql oracle

我无法按照自己的意愿显示数据。我想制作2行,每行显示如下:

Home Wins | Visitor Wins
------------------------
  3       |      2

我认为我的问题是将Case When添加到group by,因为截至目前(没有group by子句)它显示:

Home Wins | Visitor Wins
------------------------
  1       |      1

SELECT
  sum(CASE WHEN ga_home_score > ga_visitor_score THEN 1 ELSE 0 END) "Home Wins",
  sum(CASE WHEN ga_home_score < ga_visitor_score THEN 1 ELSE 0 END) "Visitor Win"
FROM dl_game g
  JOIN dl_team ht ON g.ga_home_id = ht.te_id
  JOIN dl_team vt ON g.ga_home_id = vt.te_id
WHERE ga_schedule_date <= '15-JUN-12'
GROUP BY ((CASE WHEN ga_home_score > ga_visitor_score THEN 1 ELSE 0 END),
          (CASE WHEN ga_home_score < ga_visitor_score THEN 1 ELSE 0 END));

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

SELECT  (CASE WHEN ga_home_score > ga_visitor_score THEN 'Home Wins'
              WHEN ga_home_score > ga_visitor_score THEN 'Visitor Win'
              ELSE 'Tie'
          END), COUNT(*) as cnt
FROM dl_game g JOIN
     dl_team ht
     ON g.ga_home_id = ht.te_id JOIN
     dl_team vt
     ON g.ga_home_id = vt.te_id
WHERE ga_schedule_date <= '15-JUN-12'
GROUP BY (CASE WHEN ga_home_score > ga_visitor_score THEN 'Home Wins'
               WHEN ga_home_score > ga_visitor_score THEN 'Visitor Win'
               ELSE 'Tie'
          END);

在撰写查询时,您可能不需要join。所有信息都在游戏桌中。