简体   繁体   中英

Select of calculated value always returns row

I have a database (running on postgres 9.3) of bookings of resources. This database contains a table reservations which contains beside other values the start and stop time of the reservation (as timestamp with time zone )

Now I need to know how much reservations a given company has currently active in the future in terms of total hours of all these reservations added together.

I have put together the following query that does the job:

SELECT EXTRACT(EPOCH FROM Sum(stop-start))/3600 AS total 
    FROM (reservations JOIN partners ON partner = email) 
    WHERE stop > now() AND company = 'givencompany'

This works quite well if the given company has reservations in the future. The problem I am experiencing is that when the company doesnt have any reservations the query does in fact return a row but the collumn total is empty whereas I would like it to return no row at all (or a row containing 0 if nothing is too complicated) in that case.

Is this possible to accomplish with a different SELECT or another modification to the database or does the consuming application have to check for null every time?

Sorry if my question is trivial but I am very new to databases altogether


Edit

I found out that I could default the returned value with 0 by using COALESCE but I would much prefer it if no row would be returned

Short answer : just add HAVING Sum(stop-start) IS NOT NULL at the end of query.

Long answer : This query has no explicit GROUP BY , but since it aggregates the rows with sum() , it's implicitly turned into a GROUP BY query, with all the rows matching the WHERE condition taken as one group.

See the doc on SELECT :

without GROUP BY, an aggregate produces a single value computed across all the selected rows

And about the HAVING clause:

The presence of HAVING turns a query into a grouped query even if there is no GROUP BY clause. This is the same as what happens when the query contains aggregate functions but no GROUP BY clause. All the selected rows are considered to form a single group, and the SELECT list and HAVING clause can only reference table columns from within aggregate functions. Such a query will emit a single row if the HAVING condition is true, zero rows if it is not true.

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