2017-02-28 80 views
0

我需要从上周找到顶级申请人,但我在我的SQL查询中遇到错误。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 

我做错了吗?

所以,基本上我想看到用户ID 23应用程序和用户ID 31应用。

+0

请你进行标记正在使用的DBMS。 –

+3

错误非常明显。您需要将'applications.Id'添加到group by子句中。 – Sparrow

+0

@FeryalBadili不那么简单。在OP的查询中,他选择了id,created_at,...以便至少传递错误,他需要GROUP BY中的id和create_at列。但我认为OP首先是在处理错误的查询,但他并没有完全理解他对“COUNT”函数的意图。 –

回答

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';