我想编写一个SQL查询以获取下面给出的问题解决方案-我有一个类似这样的表:
CREATE TABLE order
(
id INT,
name VARCHAR(255),
income INT,
order_date DATE
)
如果查询有问题,请原谅。
现在,我希望sql查询给出的结果是2017年用户的总收入,该用户的第一笔订单创建于2016年。
答案 0 :(得分:1)
您的订单表似乎是个奇怪的设计,但是给定了
drop table if exists t;
create table t
(
id INT,
name VARCHAR(255),
income INT,
order_date DATE
);
insert into t values
(1,'aaa',10,'2016-01-01'),(1,'aaa',10,'2017-01-01'),(1,'aaa',10,'2017-01-01'),
(2,'bbb',10,'2015-01-01'),(2,'bbb',10,'2016-01-01'),(2,'bbb',10,'2017-01-01'),
(3,'ccc',10,'2017-01-01'),(3,'ccc',10,'2017-01-01'),(3,'ccc',10,'2018-01-01')
;
一个简单的联接可能就是您所需要的
select t.name,sum(t.income)
from t
join (select name,min(year(order_date)) minyr from t group by name) s
on t.name = s.name
where year(order_date) = 2017 and minyr = 2016
group by name;
+------+---------------+
| name | sum(t.income) |
+------+---------------+
| aaa | 20 |
+------+---------------+
1 row in set (0.00 sec)
答案 1 :(得分:-1)
SELECT id, name, SUM(income)
FROM [order]
WHERE DATEPART(yyyy,order_date)='2017'
AND id IN (SELECT id FROM [order] GROUP BY id HAVING MIN(DATEPART(yyyy,order_date)) ='2016')
GROUP BY id, name