2017-02-28 82 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';