我做过一些编程和一些 SQL,但除了我自己的小项目外,我不是开发人员。 我现在有一个问题,我很想用纯 SQL 来解决,但无法真正弄清楚如何解决。 我有 2 个简单的表格,我需要从中提取月度报告,但我需要做一些计算,这是棘手的部分。 这是结构...
table
km_locations
columns
location_id INT
location_name TXT
table
km_trips
colums
trip_id INT
trip_date DATE
start_location_id INT
end_location_id INT
km_start INT
km_end INT
这里的规则让我觉得太复杂了……
- 在特定日期范围内创建报告,例如。之间 2016-02-15 和 2016-03-15。
- 用相应的替换 start_location_id 和 end_location_id km_locations 中的 location_name。
- 计算我在过去 12 个月内进行了多少次类似的旅行,以及 在单独的列中显示增量值。
- 只计算同样的行程或从家出发的行程,并且仅在当日没有其他具有相同起点和终点组合的行程时才计算在内。
下面的示例没有 total_trips 我可以用这个语句得到。
SELECT
t.trip_date,
c1.location_name AS 'trip_start',
c2.location_name AS 'trip_end',
t.km_start,
t.km_end
FROM km_trips t
LEFT JOIN km_locations c1 ON c1.location_id = t.start_location_id
LEFT JOIN km_locations c2 ON c2.location_id = t.end_location_id
WHERE t.trip_date BETWEEN '2016-02-06' AND '2016-03-10'
ORDER BY t.trip_date ASC, t.km_start ASC
想要样本日期输出
id date trip_start trip_end km_start km_end total_trips
1 2016-02-15 Home Grocery Store 10675 10681 8
2 2016-02-15 Grocery Store Gas Station 10681 10684
3 2016-02-15 Gas Station Home 10684 10689 5
4 2016-02-16 Home Grocery Store 10689 10695 9
5 2016-02-16 Grocery Store Home 10695 10701
6 2016-02-17 Home School 10701 10723 12
7 2016-02-17 School Grocery Store 10723 10739
8 2016-02-17 Grocery Store Friends House 10739 10755
9 2016-02-17 Friends House Home 10755 10767 7
10 2016-02-18 Home Friends House 10767 10783 8
11 2016-02-18 Friends House Home 10755 10767
12 2016-02-19 Home Friends House 10767 10783 9
13 2016-02-19 Friends House Grocery Store 10783 10792
14 2016-02-19 Grocery Store Home 10792 10798 10
对于 SQL 语句来说可能太多了,但我认为使用 View 、联合和一些疯狂的技能可能是可能的。 这是我从 Excel 转移过来的一个新项目,因此我愿意接受任何可以使这项工作成功的表结构建议。 现在我正在尝试使用 SQLite 来完成这项工作,但如果这是我唯一的选择,我会使用另一个数据库。
谢谢。
最佳答案
尝试相关的子查询
SELECT
t.trip_date,
c1.location_name AS 'trip_start',
c2.location_name AS 'trip_end',
t.km_start,
t.km_end,
(SELECT count(DISTINCT t2.trip_date) cnt
FROM km_trips t2
WHERE t2.trip_date < t.trip_date
AND t2.start_location_id = t.start_location_id
AND t2.end_location_id = t.end_location_id
AND (SELECT location_id FROM km_locations WHERE location_name = 'home')
IN (t2.start_location_id, t2.end_location_id)
) count
FROM km_trips t
LEFT JOIN km_locations c1 ON c1.location_id = t.start_location_id
LEFT JOIN km_locations c2 ON c2.location_id = t.end_location_id
WHERE t.trip_date BETWEEN '2016-02-06' AND '2016-03-10'
ORDER BY t.trip_date ASC, t.km_start ASC
关于mysql - super 复杂的SQL语句...可能不可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913042/