我在进行此查询时遇到麻烦,可以寻求帮助吗? 我有一个名为Measurements的表,如下所示:
+----+----------+-------+------+
| id | cost | month | year |
+----+----------+-------+------+
| 1 | 6860.52 | 5 | 2018 |
| 1 | 11993.52 | 6 | 2018 |
| 1 | 3823.2 | 7 | 2018 |
| 1 | 3557.7 | 8 | 2018 |
| 1 | 3355.92 | 9 | 2018 |
| 1 | 357.54 | 10 | 2018 |
+----+----------+-------+------+
和名为付款表
+------------+---------------+-----------------+
| id | period | payment |
+------------+---------------+-----------------+
| 1 | 2018-05-01 | 0 |
| 1 | 2018-06-01 | 0 |
| 1 | 2018-06-01 | 34327 |
| 1 | 2018-07-01 | 100 |
| 1 | 2018-07-01 | 500 |
| 1 | 2018-07-01 | 400 |
| 1 | 2018-08-01 | 0 |
+------------+---------------+-----------------+
我在尝试选择返回此内容的选择方面遇到了麻烦:
+------------+---------------+----------------+-----------------+
| id | period | date | payment |
+------------+---------------+----------------+-----------------+
| 1 | 2018-05-01 | 2018-05-01 | 0 |
| 1 | 2018-06-01 | 2018-06-01 | 34327 |
| 1 | 2018-07-01 | 2018-07-01 | 1000 |
| 1 | 2018-08-01 | 2018-08-01 | 0 |
| 1 | 2018-09-01 | NULL | 0 |
| 1 | 2018-10-01 | NULL | 0 |
+------------+---------------+----------------+-----------------+
日期来自concat(year,'-',month,'-',1)
谢谢
架构:
CREATE TABLE measurements (id INT, cost FLOAT, month INT, year INT);
INSERT INTO measurements VALUES (1, 6860.52, 5, 2018),
(1, 11993.52, 6, 2018), (1, 3823.2, 7, 2018),
(1, 3557.7, 8, 2018), (1, 3355.92, 9, 2018), (1, 357.54, 10, 2018);
CREATE TABLE payment (id INT, period DATE, payment INT);
INSERT INTO payment VALUES (1, '2018-05-01', 0),
(1, '2018-06-01', 0),(1, '2018-06-01', 34327 ),(1, '2018-07-01', 100),
(1, '2018-07-01', 500),(1, '2018-07-01', 400), (1, '2018-08-01', 0);
答案 0 :(得分:0)
您要搜索吗?
select measurements.id,
cast(concat(measurements.year, '-', measurements.month, '-01') as date) as period,
payment.period as date, sum(payment) payment
from measurements
left join payment on measurements.id = payment.id and cast(concat(measurements.year, '-', measurements.month, '-01') as date) = payment.period
group by measurements.id, measurements.year, measurements.month, payment.period
order by measurements.year, measurements.month;
答案 1 :(得分:0)
您可以在下面使用左联接尝试
select id,str_to_date(concat(year,'-',month,'-',1),'%Y-%m-%d') as period,b.period as `date`,sum(payment) as payment
from measurements a left join payment b
on a.id=b.id and str_to_date(concat(year,'-',month,'-',1),'%Y-%m-%d')=b.period
group by str_to_date(concat(year,'-',month,'-',1),'%Y-%m-%d')