Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

database - Join two similar queries made to the same table in PostgreSQL

Good evening, I have generated two queries to a PostgreSQL database, which are the following:

SELECT tarea, count(estado) AS "TotalCompletos" from tabla WHERE estado = 'Completo' GROUP BY  tarea; 

Query_1_result.png

SELECT tarea, count(estado) AS "TotalIncompletos" from tabla WHERE estado = 'Incompleto' GROUP BY  tarea;

Query_2_result.png

My question is, how can I merge the above two queries into one query in order to produce a result similar to the following?

Expected_result.png

I have used UNION but I do not get the expected results. Attached is some sample code from the database I am using: Demo_DB

question from:https://stackoverflow.com/questions/65894454/join-two-similar-queries-made-to-the-same-table-in-postgresql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
with q1 as (
SELECT tarea, count(estado) AS "TotalCompletos" from tabla WHERE estado = 'Completo' GROUP BY  tarea
),
q2 as (
SELECT tarea, count(estado) AS "TotalIncompletos" from tabla WHERE estado = 'Incompleto' GROUP BY  tarea
)
select tarea, coalesce("TotalCompletos", 0) as "TotalCompletos", coalesce("TotalIncompletos", 0) as "TotalIncompletos"
from q1 full join q2 using (tarea);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...