Можете ли вы COUNT () результат оператора CASE с псевдонимом "AS" что-то - PullRequest
0 голосов
/ 06 февраля 2020

Я пытаюсь выяснить, могу ли я посчитать столбцы Wins and Loses, которые являются результатом моей функции CASE с псевдонимом. Я включил свои таблицы, вставки, оператор выбора и изображение вывода. На изображении вы увидите столбцы «Победитель» и «Проигравший», созданные CASE. Я надеюсь как-то СЧИТАТЬ () тех, кто с предложением where в названии команды.

Моя цель - показать каждой команде выигрыш / поражение. Так что в этом случае в столбцах должно быть указано TeamName, Wins, Loses. И под ними в таком порядке должны быть Sharks, 2, 0.

Таблицы:

create table team (
  teamID        number(2,0) not null,
  teamAbb       varchar2(3),
  teamName      varchar2(20),
  location      varchar2(20),
  division      varchar2(20),
  conference    varchar2(20),
  constraint pk_team primary key (teamID)
);

create table game(
 gameID     number(2,0) not null,
 gameDate   date,
 homeTeam   number(2,0),
 homeScore  number(2,0),
 awayTeam   number(2,0),
 awayScore  number(2,0),
 constraint pk_game primary key (gameID),
 constraint fk_homeTeam foreign key (homeTeam) references team (teamID),
 constraint fk_awayTeam foreign key (awayTeam) references team (teamID)
);

Вставки:

DECLARE

BEGIN

insert into team values(10, 'ANA', 'Ducks', 'Anaheim', 'Pacific', 'Western');
insert into team values(11, 'ARI', 'Coyotes', 'Arizona', 'Pacific', 'Western');
insert into team values(12, 'BOS', 'Bruins ', 'Boston', 'Atlantic', 'Eastern');
insert into team values(13, 'BUF', 'Sabers ', 'Buffalo', 'Atlantic', 'Eastern');
insert into team values(14, 'CGY', 'Flames ', 'Calgary', 'Pacific', 'Western');
insert into team values(15, 'CAR', 'Hurricanes', 'Carolina', 'Metropolitan', 'Eastern');
insert into team values(16, 'CHI', 'Blackhawks', 'Chicago', 'Central', 'Western');
insert into team values(17, 'COL', 'Avalanche', 'Colorado', 'Central', 'Western');
insert into team values(18, 'CBJ', 'Blue Jackets', 'Columbus', 'Metropolitan', 'Eastern');
insert into team values(19, 'DAL', 'Stars', 'Dallas', 'Central', 'Western');
insert into team values(20, 'DET', 'Red Wings', 'Detroit', 'Atlantic', 'Eastern');
insert into team values(21, 'EDM', 'Oilers', 'Edmonton', 'Pacific', 'Western');
insert into team values(22, 'FLA', 'Panthers', 'Florida', 'Atlantic', 'Eastern');
insert into team values(23, 'LAK', 'Kings', 'Los Angeles', 'Pacific', 'Western');
insert into team values(24, 'MIN', 'Wild', 'Minnesota', 'Central', 'Western');
insert into team values(25, 'MTL', 'Canadiens', 'Montreal', 'Atlantic', 'Eastern');
insert into team values(26, 'NSH', 'Predators', 'Nashville', 'Central', 'Western');
insert into team values(27, 'NJD', 'Devils', 'New Jersey', 'Metropolitan', 'Eastern');
insert into team values(28, 'NYI', 'Islanders', 'New York', 'Metropolitan', 'Eastern');
insert into team values(29, 'NYR', 'Rangers', 'New York ', 'Metropolitan', 'Eastern');
insert into team values(30, 'OTT', 'Senators', 'Ottawa', 'Atlantic', 'Eastern');
insert into team values(31, 'PHI', 'Flyers', 'Philadelphia', 'Metropolitan', 'Eastern');
insert into team values(32, 'PIT', 'Penguins', 'Pittsburgh', 'Metropolitan', 'Eastern');
insert into team values(33, 'SJS', 'Sharks', 'San Jose', 'Pacific', 'Western');
insert into team values(34, 'STL', 'Blues', 'St. Louis', 'Central', 'Western');
insert into team values(35, 'TBL', 'Lightning', 'Tampa Bay', 'Atlantic', 'Eastern');
insert into team values(36, 'TOR', 'Maple Leafs', 'Toronto', 'Atlantic', 'Eastern');
insert into team values(37, 'VAN', 'Canucks', 'Vancouver', 'Pacific', 'Western');
insert into team values(38, 'VGK', 'Golden Knights', 'Vegas', 'Pacific', 'Western');
insert into team values(39, 'WSH', 'Capitals', 'Washington', 'Metropolitan', 'Eastern');
insert into team values(40, 'WPG', 'Jets', 'Winnipeg', 'Central', 'Western');

COMMIT;

END;

DECLARE

BEGIN

insert into game values (1, to_date('01-11-2020','mm-dd-yyyy'), 33, 2, 20, 1);
insert into game values (2, to_date('01-13-2020','mm-dd-yyyy'), 11, 5, 33, 6);
insert into game values (3, to_date('03-04-2020','mm-dd-yyyy'), 20, null, 13, null);

COMMIT;

END;

Мое предложение выбора:

 SELECT gameDate,
 t1.teamName AS homeTeam, g.homeScore, 
 t2.teamName AS awayTeam, g.awayScore, 
  CASE WHEN homescore > awayscore THEN t1.teamname
  WHEN awayscore > homescore THEN t2.teamname
  ELSE null END AS winner,
  CASE WHEN homescore < awayscore THEN t1.teamname
  WHEN awayscore < homescore THEN t2.teamname
  ELSE null END AS loser
FROM game g
 INNER JOIN team t1 
 ON t1.teamID = g.homeTeam
 INNER JOIN team t2 
 ON t2.teamID = g.awayTeam;

Query Result

Ответы [ 2 ]

1 голос
/ 07 февраля 2020

Я бы выбрал всех победителей и всех проигравших и подсчитывал их выигранные и проигранные игры на лету. Затем возьмите команды и присоединитесь к двум пунктам.

with winners as
(
  select
   case when homescore > awayscore then hometeam else awayteam end as teamid,
   count(*) as total
  from game
  where homescore <> awayscore
  group by case when homescore > awayscore then hometeam else awayteam end
)
, losers as
(
  select
    case when homescore < awayscore then hometeam else awayteam end as teamid,
    count(*) as total
  from game
  where homescore <> awayscore
  group by case when homescore < awayscore then hometeam else awayteam end
)
select
  t.name,
  coalesce(w.total, 0) as won_games,
  coalesce(l.total, 0) as lost_games
from team t
left join winners w on w.teamid = t.teamid
left join losers l on l.teamid = t.teamid
order by t.name;
1 голос
/ 07 февраля 2020

Если мы обработаем запрос, который вы уже написали, все, что осталось, - это выбрать победителей и проигравших и подсчитать их выигрыши / проигрыши.

SQL> with your_query as (
  2  SELECT gameDate,
  3   t1.teamName AS homeTeam, g.homeScore,
  4   t2.teamName AS awayTeam, g.awayScore,
  5    CASE WHEN homescore > awayscore THEN t1.teamname
  6    WHEN awayscore > homescore THEN t2.teamname
  7    ELSE null END AS winner,
  8    CASE WHEN homescore < awayscore THEN t1.teamname
  9    WHEN awayscore < homescore THEN t2.teamname
 10    ELSE null END AS loser
 11  FROM game g
 12   INNER JOIN team t1
 13   ON t1.teamID = g.homeTeam
 14   INNER JOIN team t2
 15   ON t2.teamID = g.awayTeam
 16   )
 17  -- fetch winners and count their wins
 18   select
 19     winner,
 20     count(*) cnt_win,
 21     0 cnt_lose
 22    from your_query
 23    where winner is not null
 24    group by winner
 25  union all
 26  -- fetch losers and count their loses
 27    select loser,
 28      0 cnt_win,
 29      count(*) cnt_lose
 30    from your_query
 31    where loser is not null
 32    group by loser;

WINNER                  CNT_WIN   CNT_LOSE
-------------------- ---------- ----------
Sharks                        2          0
Coyotes                       0          1
Red Wings                     0          1

SQL>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...