我需要找到上周的顶级申请人,但我的SQL查询中出现错误。
var queryString = "select id, created_at, user_id, count(id) as cnt from "+
"applications where id in (select id from applications where "+
"created_at > current_date - interval '1 week') group by user_id";
data.sql
insert into listings (id, created_at, created_by, name, description) values
(1, '2015-01-15 11:00', 1, 'Join us conquering the world!', 'This is your best chance to be on the right side of the equation...')
;
insert into listings (id, created_at, created_by, name, description) values
(1, '2015-01-15 11:00', 1, 'Join us conquering the world!', 'This is your best chance to be on the right side of the equation...')
;
insert into listings (id, created_at, created_by, name, description) values
(2, '2017-01-29 11:00', 1, 'Join us conquering the world!', 'Holla ho')
;
insert into listings (id, created_at, created_by, name, description) values
(3, '2017-01-15 11:00', 1, 'Join us conquering the world!', 'Hey ya')
;
insert into applications (created_at, user_id, listing_id, cover_letter) values
('2017-02-23 12:00', 2, 1, 'Hello, ...')
;
INSERT INTO APPLICATIONS (CREATED_AT, USER_ID, LISTING_ID, COVER_LETTER) VALUES
('2017-02-24 12:00', 2, 2, 'HELLO, ...')
;
INSERT INTO APPLICATIONS (CREATED_AT, USER_ID, LISTING_ID, COVER_LETTER) VALUES
('2017-02-22 12:00', 2, 2, 'HELLO, ...')
;
INSERT INTO APPLICATIONS (CREATED_AT, USER_ID, LISTING_ID, COVER_LETTER) VALUES
('2017-02-25 12:00', 3, 1, 'HELLO, ...')
;
这是错误:
column "applications.id" must appear in the GROUP BY clause or be used in an aggregate function
我做错了什么?
所以,基本上我希望看到用户2
用3
个应用,用户ID为3
,用1
个应用。
答案 0 :(得分:1)
您可能打算进行此查询:
select user_id, count(id) as cnt
from applications
where id in (select id
from applications
where created_at > current_date - interval '1 week'
)
group by user_id;
请注意从select
。
如果我们假设id
实际上是唯一的,您可以这样做:
select user_id, count(id) as cnt
from applications
group by user_id
having max(created_at) > current_date - interval '1 week';