查找未定期增加的行

时间:2015-12-28 04:12:09

标签: sql postgresql window-functions

我有一张表来存储产品的投票和评论者。审稿人的价值会随着时间的推移而增加。

CREATE TABLE product
(
  product_id character varying(255),
  voting integer,
  reviewers integer,
  created_at timestamp without time zone
);

数据

+------------+-----------+--------+---------------------+
| product_id | reviewers | voting |     created_at      |
+------------+-----------+--------+---------------------+
| B000GRMH8A |        50 |      5 | 2015-11-19 00:41:30 |
| B000GRMH8A |        38 |      4 | 2015-11-17 00:42:03 |
| B000GRMH8A |        20 |      2 | 2015-11-15 00:41:23 |
| HXXRSEW    |        50 |      3 | 2015-11-19 00:41:30 |
| HXXRSEW    |        72 |      2 | 2015-11-17 00:42:03 |
| HXXRSEW    |        48 |      1 | 2015-11-15 00:41:23 |
+------------+-----------+--------+---------------------+

如何查找包含无效数据的所有行?

enter image description here

1 个答案:

答案 0 :(得分:2)

假设您的问题中有错误,例如评论,则可能是您的查询:

SELECT *
FROM  ( 
   SELECT *, lag(reviewers) OVER (PARTITION BY product_id
                                  ORDER BY created_at) reviewers_prev
   FROM   product
   ) sub
WHERE  reviewers < reviewers_prev;

在子查询中使用window function lag(),然后过滤审核人数减少的行 - 冒犯您的规则:reviewers value will increase by time

SQL Fiddle.