我在表格中有4行:玩家
PlayerName (8 distinct players)
Performance
good
bad
Salary (integer)
PositionPlayed (5 distinct positions)
我希望获得一个输出,其中显示了球员的名字以及当表现糟糕时球员在特定位置的比赛次数。
James | Kobe | Jordan
Center 5 | 8 | 5
PF 3 | 5 | 2
PG 2 | 1 | 0
我是SQL的新手,我甚至不知道从哪里开始这样的事情。请协助或提供一些指导,了解如何搜索我需要学习的此类查询
由于
答案 0 :(得分:0)
如果你可以忍受"翻转"如何呈现该表,这将实现翻转布局的生成:
SELECT
PlayerName
, COUNT(CASE WHEN PositionPlayed = 'Center' THEN PlayerName END) AS "Center"
, COUNT(CASE WHEN PositionPlayed = 'PF' THEN PlayerName END) AS "PF"
, COUNT(CASE WHEN PositionPlayed = 'PG' THEN PlayerName END) AS "PG"
FROM Players
WHERE Performance = 'bad'
GROUP BY PlayerName
ORDER BY PlayerName
每个位置需要一行SQL代码,但您可以根据需要报告任意数量的玩家,而无需更改该查询。
您可以扩展该逻辑,例如通过为“好”提供一些列。以及其他因为“坏”的事。 e.g。
SELECT
PlayerName
, COUNT(CASE WHEN Performance = 'good' and PositionPlayed = 'Center' THEN PlayerName END) AS "Center"
, COUNT(CASE WHEN Performance = 'good' and PositionPlayed = 'PF' THEN PlayerName END) AS "PF"
, COUNT(CASE WHEN Performance = 'good' and PositionPlayed = 'PG' THEN PlayerName END) AS "PG"
, COUNT(CASE WHEN Performance = 'bad' and PositionPlayed = 'Center' THEN PlayerName END) AS "Center"
, COUNT(CASE WHEN Performance = 'bad' and PositionPlayed = 'PF' THEN PlayerName END) AS "PF"
, COUNT(CASE WHEN Performance = 'bad' and PositionPlayed = 'PG' THEN PlayerName END) AS "PG"
FROM Players
GROUP BY PlayerName
ORDER BY PlayerName
;
答案 1 :(得分:0)
假设你的表结构是这样的 -
Create table player(
id int(11) not null auto_increment,
player_name varchar(20) not null,
performance varchar(4) not null,
position_played varchar(2) not null,
constraint primary key (id)
);
并有一些样本数据,如 -
insert into player(player_name, performance, position_played)
values('a', 'good', 'p1'),
('a', 'bad', 'p3'),
('a', 'bad', 'p3'),
('b', 'good', 'p2'),
('b', 'bad', 'p2'),
('b', 'good', 'p1'),
('c', 'bad', 'p1'),
('c', 'bad', 'p2'),
('c', 'good', 'p3');
通过运行此查询生成所需的输出 -
SELECT P.`position_played`,
COUNT(
CASE
WHEN P.`performance`='bad' and p.`player_name`='a'
THEN p.player_name
ELSE NULL
END
) AS 'Player A',
COUNT(
CASE
WHEN P.`performance`='bad' and p.`player_name`='b'
THEN p.player_name
ELSE NULL
END
) AS 'Player B',
COUNT(
CASE
WHEN P.`performance`='bad' and p.`player_name`='c'
THEN p.player_name
ELSE NULL
END
) AS 'Player C'
FROM player P
GROUP BY P.`position_played`;
查找输出结果blog