简体   繁体   English

如何在X或HA上建立查询

[英]How to build query WHERE X OR HAVING Y

My data is a parent table named sales and a child table named sale_lines . 我的数据是一个名为sales的父表和一个名为sale_lines的子表。 I'd like to select all records from the sales table where sale.customer_id=X OR SUM(sale_lines.total)>=Y . 我想从sales表中选择所有记录,其中sale.customer_id=XSUM(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. customer_id条件将放在WHERE子句中,并且在HAVING子句中具有SUM(sale_lines.total)>Y是有意义的。 My problem is how to have a logical OR between the WHERE and HAVING clauses. 我的问题是如何在WHEREHAVING子句之间进行逻辑OR 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: 您需要在having子句中执行此操作:

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. 由于存在or ,因此无法在聚合之前进行过滤。

Actually, if you want the records from the sales table (and not the aggregations), then something like this is appropriate: 实际上,如果您希望从sales表中获得记录(而不是聚合),则可以使用如下所示的方法:

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
                       );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM