SQL Where子句对于每一行都不同

时间:2018-05-29 10:45:02

标签: sql postgresql

我有一张看起来像这样的桌子 enter image description here

我需要计算具有特定答案ID的条目数 但是,我需要计数只计算用户的最新答案,即。我需要在哪里 动态检查每个条目的子句,它是用户的最新答案。

这是我目前的开始 我怎样才能真正发挥作用?

SELECT COUNT(DISTINCT social.useranswers.uid)
FROM useranswers
WHERE useranswers.answerid = $1;
    AND userAnswers.date = (
        SELECT MAX(userAnswers.date) 
        FROM userAnswers 
        WHERE uid=uid
        )

2 个答案:

答案 0 :(得分:0)

您可以在limit

中使用subquery子句
select count(*)
from useranswers u
where id = (select u1.id
            from useranswers u1
            where u1.uid = u.uid
            order by date desc
            limit 1
           );

答案 1 :(得分:0)

我怀疑我理解正确,解释不够清楚,但您可以使用此代码获取具有特定uid的每个最后id条目的数量

CREATE LOCAL TEMPORARY TABLE tmp (
      id       CHAR(1),
      uid      VARCHAR,
      dt       DATE,
      storyid  CHAR(1),
      answerid CHAR(1)
    );

    --Just some sample data for testing purpose
    INSERT INTO tmp VALUES ('1', '1', '2018-05-20', '1', '1');
    INSERT INTO tmp VALUES ('2', '1', '2018-05-21', '1', '1');
    INSERT INTO tmp VALUES ('1', '1', '2018-05-22', '1', '1');
    INSERT INTO tmp VALUES ('4', '2', '2018-05-21', '1', '1');
    INSERT INTO tmp VALUES ('5', '2', '2018-05-22', '1', '1');
    INSERT INTO tmp VALUES ('6', '3', '2018-05-20', '1', '1');
    INSERT INTO tmp VALUES ('7', '4', '2018-05-21', '1', '1');
    INSERT INTO tmp VALUES ('8', '4', '2018-05-21', '2', '1');
    INSERT INTO tmp VALUES ('1', '4', '2018-05-22', '2', '1');

    SELECT
      count(*)
      , uid
    FROM (
           SELECT
             id
             , uid
             , dt
             , row_number()
               OVER (
                 PARTITION BY uid
                 ORDER BY dt DESC ) num
           FROM tmp
         ) tt
    WHERE num = 1 AND id = '1'
    GROUP BY uid;