Skip to main content
2 of 5
added 12 characters in body
Erwin Brandstetter
  • 186.6k
  • 28
  • 465
  • 639

I think this is what you are after:

SELECT count( sum_price < 10.5 OR NULL) AS "DA $0 - $10" , count(sum_price >= 10.5 AND sum_price < 20.5 OR NULL) AS "DA $11 - $20" , count(sum_price >= 20.5 AND sum_price < 30.5 OR NULL) AS "DA $21 - $30" FROM ( SELECT sum(d."SettlementPointPrice") AS sum_price FROM public.da d JOIN public.rt_aggregate r USING ("DeliveryDate", "SettlementPointName") WHERE d."SettlementPointName" = 'John' AND d."DeliveryDate" >= '2015-02-01' AND d."DeliveryDate" <= '2015-02-20' AND r."DeliveryHour" = 14 AND date_part('hour', d."DeliveryHour") = r."DeliveryHour" GROUP BY d."SettlementPointPrice", -- really? d."SettlementPointName" ) sub; 

At least that's what your given query implies.

It would make a lot more sense to me without d."SettlementPointPrice" in the GROUP BY clause, though.

Or, while your predicate d."SettlementPointName" = 'John' is filtering a single value for "SettlementPointName" anyway, simplify to:

SELECT count( d."SettlementPointPrice" < 10.5 OR NULL) AS "DA $0 - $10" , count(d."SettlementPointPrice" >= 10.5 AND d."SettlementPointPrice" < 20.5 OR NULL) AS "DA $11 - $20" , count(d."SettlementPointPrice" >= 20.5 AND d."SettlementPointPrice" < 30.5 OR NULL) AS "DA $21 - $30" FROM public.da d JOIN public.rt_aggregate r USING ("DeliveryDate", "SettlementPointName") WHERE d."SettlementPointName" = 'John' AND d."DeliveryDate" >= '2015-02-01' AND d."DeliveryDate" <= '2015-02-20' AND r."DeliveryHour" = 14 AND date_part('hour', d."DeliveryHour") = r."DeliveryHour"; 
Erwin Brandstetter
  • 186.6k
  • 28
  • 465
  • 639