简体   繁体   中英

postgresql How show most frequent value per day date

I've got a problem with a query that is supposed to return the value which occur most per date

+------------+------------------+
|    Date    |      value       |
+------------+------------------+
| 2020-01-01 | Programmer       |
| 2020-01-02 | Technician       |
| 2020-01-03 | Business Analyst |
+------------+------------------+

So far I have done

select count(headline) as asd, publication_date, employer -> 'name' as dsa from jobhunter
group by publication_date,dsa
ORDER BY publication_date  DESC

But it shows 2020-12-31 19:06:00 instead of just YYYY-MM-DD Any idea on how to fix this? enter image description here

Test data:

create table tbl (
    id serial primary key,
    row_datetime TIMESTAMP,
    row_val VARCHAR(60)
);

insert into tbl (row_datetime, row_val) values ('2021-01-01 00:00:00', 'a');
insert into tbl (row_datetime, row_val) values ('2021-01-01 01:00:00', 'a');
insert into tbl (row_datetime, row_val) values ('2021-01-01 02:00:00', 'b');
insert into tbl (row_datetime, row_val) values ('2021-01-02 00:00:00', 'a');
insert into tbl (row_datetime, row_val) values ('2021-01-02 01:00:00', 'b');
insert into tbl (row_datetime, row_val) values ('2021-01-02 02:00:00', 'b');

Example query:

SELECT dt, val, cnt
FROM (
   SELECT dt, val, cnt, ROW_NUMBER() OVER (PARTITION BY dt ORDER BY cnt DESC) AS row_num
   FROM (
      SELECT dt, val, COUNT(val) AS cnt
      FROM (
         SELECT DATE(row_datetime) AS dt, row_val AS val FROM tbl
      ) AS T1 GROUP BY dt, val
   ) AS T2
) AS T3
WHERE row_num=1
ORDER BY dt ASC

You can additionally customize your query to optimize the performance, get more fields, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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