Skip to content
Advertisement

How can I combine these 3 different queries into one?

I have 3 queries in a MySQL database that output all the same fields except the last one, which is a calculation. I would like, if possible, to combine them into one query that outputs the common fields plus the additional calculated fields.

These are the queries:

Query 1:

Query 2:

Query 3:

You can notice that the first 4 fields in the SELECT are always the same. The output I’m looking for is something like:

CF: calculated field, last field in the SELECT of the corresponding query

Advertisement

Answer

The following query should get the job done. I changed the WHERE condition on tipo_acceso to a IN clause and used conditional aggreation to compute the counts and the min.

Other notable points:

  • all non-aggregated columns must appear in the GROUP BY clause; on any RDBMS other than old versions of MySQL, failing to comply with this rule generates a fatal error

  • I used table aliases to shorten the query

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement