mysql - 每个时间范围内的 3 个 Mysql 表之间的查询
问题描述
我正在研究一个小型数据库,该数据库记录不同客户在不同时间段内不同物业的租金。我在下面留下了我的表格结构的摘要示例。
+--------------+
| customer |
|--------------|
| id |
| name |
+--------------+
+--------------+
| property |
|--------------|
| id |
| number |
| address |
+--------------+
+--------------+
| rental |
|--------------|
| id |
| date_init |
| date_end |
| month_payment|
| customer_id |
| property_id |
+--------------+
我现在想通过咨询找出以下内容:在我的租赁表中,我保留了我同意每月取消租赁的客户、财产和金额,因此在这一年中会有客户租用不同的财产. 我如何知道我的客户在某个时间段内产生了多少钱,例如如果我有以下记录:
customer
+--------------+
| id | name |
|--------------|
| 1 | jhon doe|
| 2 | alex gs |
| 3 | martha |
+--------------+
property
+------------------------------------+
| id | number | address |
--------------------------------------
| 1 | 5643 | chicago |
| 2 | 1023 | toronto |
| 3 | 3445 | atlanta |
+------------------------------------+
rental
+-------------------------------------------------------------------+
| id | customer_id | property_id | date_init | date_end | amount |
---------------------------------------------------------------------
| 1 | 1 | 1 | 2019-01-05 | 2019-06-05 |3000 |
| 2 | 2 | 2 | 2019-04-10 | 2019-10-10 |1800 |
| 3 | 1 | 3 | 2019-02-14 | 2019-11-14 |1000 |
+-------------------------------------------------------------------+
然后作为参数给出一段时间,例如:2019-01-01
仅2019-12-30
获取匹配并具有以下结果的记录:
+---------------------+
| customer | total |
|----------------------
| jhon doe | 24,000 |
| alex gs | 10,800 |
+---------------------+
在这种情况下,John Doe 客户租了 2 处房产,第 5 个月租了 3000 共 15000,另一处租了 9 个月至 1000 共 9000,所以可以用这种类型的查询数据?我还没有查询作为示例,因为我不知道如何处理这个问题。我正在努力,一旦我有东西我会更新我的问题,谢谢!
解决方案
编辑——
您需要使用 SUM() 和 JOIN 然后指定要返回的字段。
SELECT c.name AS customer, SUM(r.amount) AS total
FROM rentals r
INNER JOIN customer c ON c.id = r.customer_id
WHERE r.date_end >= $START AND r.date_end <= $END
GROUP BY r.customer_id
http://www.sqlservertutorial.net/sql-server-aggregate-functions/sql-server-sum/
推荐阅读
- fortran - 将派生类型作为参数的函数作为 Fortran 中的参数传递
- java - 如何使用 BufferedReader 获取整数
- android - 使用 Android UI Automator 在辅助显示器上测试内容
- php - PHP - 获取整数两侧的范围
- c++ - 如何使用 C++ 绘制形状、线条和圆弧
- spool - 如何获取 PCL 打印文件的压缩类型?
- regex - 正则表达式将字符串分成组
- asp.net - 核心 ASP.NET 项目 Azure 构建管道
- javascript - Firebase 实时数据库 - 如何订阅数据库添加?
- javascript - 如何使用 Material-UI 创建自定义按钮?