2012-11-08 2 views
3

특정 방식으로 정렬 된 쿼리의 행의 마지막 1/x 부분을 선택하고 싶습니다. 어떻게해야합니까?쿼리에서 마지막 x % 행을 어떻게 선택합니까?

나는

SELECT avg(smilies_count) 
FROM posts AS p 
WHERE time >= (???) -- I only want the last 25% of posts in this thread 
GROUP BY thread_id; -- each thread can have more than 1 post, but I still only 
        -- want to consider the last 25% of posts in my average 

같은 것을 마련했지만 나는 매우 울퉁불퉁 한 표현을 초래하지 것이라고 ???에 어떤 내용이 너무 확실하지 않다.

편집

나는 ???

SELECT min(p2.time) 
FROM posts AS p2 
WHERE p2.thread_id = p.thread_id 
ORDER BY p2.time DESC 
LIMIT count(*)/4 

을 퍼팅 시도했지만, 그것은 단지이 마지막으로해야 할 경우에 대비 버전의 나에게

Error: misuse of aggregate function count() 
+0

게시물 테이블에 post_id 열이 있습니까? 및 솔루션 sqlite 만 있어야합니까? – pkmiec

+0

@Dooh 예, 나는 post_id를 가지고 있으며, SQLite에서도 작동하는 한 모든 솔루션이 잘되어야합니다. – wrongusername

답변

2

난 당신이 기본적으로 모든 스레드에서 마지막 게시물의 25 %를한다고 가정하고, 나중에 작업이 당신에게 달려 있습니다.

내가 맞다면,이 코드는 당신을 위해 작동합니다 (MS-SQL 용으로 작성, 쉽게 SQLite에 휴대용이어야 함) : 그것은 주로 하위 쿼리로 확대됨에 쿼리 아니라고

CREATE TABLE posts (
    post_id INT, 
    thread_id INT 
) 

INSERT INTO posts(post_id, thread_id) VALUES (1, 1) 
INSERT INTO posts(post_id, thread_id) VALUES (2, 2) 
INSERT INTO posts(post_id, thread_id) VALUES (3, 2) 
INSERT INTO posts(post_id, thread_id) VALUES (4, 3) 
INSERT INTO posts(post_id, thread_id) VALUES (5, 3) 
INSERT INTO posts(post_id, thread_id) VALUES (6, 3) 
INSERT INTO posts(post_id, thread_id) VALUES (7, 3) 
INSERT INTO posts(post_id, thread_id) VALUES (8, 3) 
INSERT INTO posts(post_id, thread_id) VALUES (9, 3) 
INSERT INTO posts(post_id, thread_id) VALUES (10, 3) 
INSERT INTO posts(post_id, thread_id) VALUES (11, 3) 

SELECT src.* 
FROM (
    SELECT post_number = (
     SELECT 1 + COUNT(*) 
     FROM posts pp 
     WHERE p.post_id > pp.post_id 
     AND p.thread_id = pp.thread_id 
    ), 
    post_id, 
    thread_id 
    FROM posts p 
) src 
JOIN (
    SELECT thread_id, cnt = COUNT(*) 
    FROM posts 
    GROUP BY thread_id 
) counts 
ON src.thread_id = counts.thread_id 
WHERE (CONVERT(FLOAT, src.post_number)/CONVERT(FLOAT, counts.cnt)) >= 0.75 

참고 post_number를 얻습니다. OVER 절을 지원하는 DBMS의 경우 더 나은 방법으로 OVER 절을 사용하여 작성할 수 있습니다.

+0

많은 감사합니다, 마침내 그것을 작동 시켰습니다. SQL이이 작업에 가장 적합한 언어가 아닐 수도 있습니다. 하하 – wrongusername

-1

했다 (25) 전체 게시물의 비율 :

(210)
select 
    avg(1.0 * smilies_count) avg_count, 
from (select top 25% * from posts order by time desc) last_posts 

그리고이 모든 스레드에 대한 포스트의 지난 25 %를 하나 더 :

select 
    avg(1.0 * smilies_count) avg_smilies 
from (
    select 
    thread_id, post_id, smilies_count, 
    row_number() over (partition by thread_id order_by time desc) row_num 
    from posts 
) p 
join (select thread_id, count(*) cnt from posts group by thread_id) c on 
    p.thread_id = c.thread_id 
where 
    p.row_num < 0.25 * c.cnt 
group by 
    p.thread_id 
+2

질문에 암시 적으로 언급 된 모든 스레드에 대해 마지막 25 % 게시물을 가져 오는 요구 사항을 놓친 것 같아요 (샘플 쿼리의 "그룹 ID 별 그룹") – pkmiec

+0

@Dooh는 암시 적으로'group by ' 절하지만 괜찮아 :) – pkuderov

+0

@pkuderov'last_post'가 무엇을 설명해 주시겠습니까? –

관련 문제