简体   繁体   中英

How to build query WHERE X OR HAVING Y

My data is a parent table named sales and a child table named sale_lines . I'd like to select all records from the sales table where sale.customer_id=X OR SUM(sale_lines.total)>=Y .

The customer_id condition will go in the WHERE clause and it makes sense to have the SUM(sale_lines.total)>Y in the HAVING clause. My problem is how to have a logical OR between the WHERE and HAVING clauses. Is this possible? If so, how?

I know how to do this with a sub-query, but I'm trying to develop an automated query generation solution and I'd like to avoid the complexity of dealing with sub-queries.

You need to do this in the having clause:

select . . .
from . . .
group by s.customer_id, . . .
having s.customer_id = X or sum(s.total) > Y;

The query might look like:

select s.customer_id, sum(s.total)
from sales s
group by s.customer_id
having s.customer_id = X or sum(s.total) > Y;

Because of the or , you cannot filter before aggregation.

Actually, if you want the records from the sales table (and not the aggregations), then something like this is appropriate:

select s.*
from sales s
where s.customer_id = X or
      s.customer_id in (select s2.customer_id
                        from sales s2
                        group by s2.customer_id
                        having sum(s2.total) > Y
                       );

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