我在数据库中有行表:
id
,kills
,deaths
,week
我如何选择kills
week=1
和deaths
哪里week=2
在一个表中?
答案 0 :(得分:3)
您可以使用两个单独的select语句:
SELECT(
(SELECT kills FROM tablename WHERE week = 1),
(SELECT deaths FROM tablename WHERE week = 2)
)
这将为周期= 1的杀戮创建一列,为周= 2的死亡创建另一列。
您可以使用UNION
关键字将它们组合在一起:
SELECT 'week 1 - kills' as source, kills FROM tablename WHERE week = 1
UNION
SELECT 'week 2 - deaths' as source, deaths FROM tablename WHERE week = 2
这两种方法需要对表进行双重扫描。
如果您需要聚合函数,另一种方法是使用条件子句@Juan Carlos Oropeza的解决方案。但是,正如所指出的那样,将这两个陈述合并为一个可能不是最佳选择。
答案 1 :(得分:2)
您可以使用条件聚合
SELECT SUM (CASE WHEN week = 1 THEN kills END) as total_kills_week1,
SUM (CASE WHEN week = 2 THEN deaths END) as total_deaths_week2
FROM YourTable