结合两个具有不同WHERE条件的查询

时间:2019-03-22 04:06:56

标签: sql database sqlite

我正在尝试使用sqlite3从同一张表中获取具有不同WHERE条件的两个查询的结果。我可以使查询独立运行,但无法将它们组合在一起。

查询1:

SELECT COUNT(*) AS 'With Survivors', Day FROM crashes 
WHERE Fatalities < Aboard Group BY DIndex

结果:

    With Survivors  Day
0   231             Monday
1   262             Tuesday
2   243             Wednesday
3   271             Thursday
4   255             Friday
5   254             Saturday
6   216             Sunday

查询2:

SELECT Count(*) AS 'Total Crashes', Day FROM crashes GROUP BY DIndex

结果:

    Total Crashes  Day
0   713            Monday
1   796            Tuesday
2   796            Wednesday
3   818            Thursday
4   797            Friday
5   741            Saturday
6   607            Sunday

我想将它们结合起来,以便获得以下信息:

    With Survivors  Total Crashes   Day
0   231             713             Monday
1   262             796             Tuesday
2   243             796             Wednesday
3   271             818             Thursday
4   255             797             Friday
5   254             741             Saturday
6   216             607             Sunday

我对SQL还是很陌生,因此尽管我尝试搜索答案,但甚至不确定是否在搜索引擎中输入了正确的查询。

2 个答案:

答案 0 :(得分:0)

您可以使用UNION合并两个SELECT语句

SELECT COUNT(*) AS 'With Survivors', Day FROM crashes 
WHERE Fatalities < Aboard Group BY DIndex
UNION
SELECT Count(*) AS 'Total Crashes', Day FROM crashes GROUP BY DIndex;

答案 1 :(得分:0)

SQLite支持CASE表达式,因此应该可以正常工作

SELECT 
   Sum( Case WHEN Fatalities < Aboard THEN 1 ELSE 0 end ) AS 'With Survivors',
   Count(*) AS 'Total Crashes', 
   Day 
FROM crashes 
GROUP BY DIndex