简体   繁体   English

如何在单个查询中选择带有计数和限制的postgres中的数据

[英]How to select data in postgres with count and limit in a single query

A PostgreSQL table with data in the format 数据格式为PostgreSQL的表

the table name is tbl1 tbl1 表名称是tbl1 tbl1

id -- RCODE -- CCODE -- LDATA
1     123      50        p1
2     124      51        p2
3     126      50        p3

....................... ......... ..... . ....................................................................

23     116      56        p3
24     126      50        p9
25     126      50        p3
26     136      56        p5
27     126      50        p3
28     146      52        p7

My problem is how to find the count of CCODE =50 from last 7 records of the db having RCODE =126 我的问题是如何从具有RCODE =126的数据库的最后7条记录中查找CCODE =50的计数

Use a subquery to generate an intermediate table a which contains the last 7 records of the db having RCODE=126 . 使用子查询生成中间表a ,该中间表包含具有RCODE = 126的数据库最后7条记录 Then run COUNT over it WHERE CCODE=50 . 然后在其WHERE CCODE=50运行COUNT Query: 查询:

SELECT COUNT(*)
FROM (
    SELECT CCODE
    FROM tbl1
    WHERE RCODE = 126
    ORDER BY id DESC LIMIT 7
) AS a
WHERE CCODE = 50
select count(*) as total
from (
    select CCODE
    from tbl1
    where RCODE = 126
    order by id desc
    limit 7
    ) s
where CCODE = 50

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM