如果所有行都符合特定条件,则从一列中获取不同的值
Getting a distinct value from one column if all rows matches a certain criteria
如果 table 中的所有行都符合特定条件,我正在尝试找到一个高性能且易于阅读的查询以从一列中获取不同的值。
我有一个 table 跟踪电子商务订单以及它们是否按时交付、内容和架构如下:
> select * from orders;
+----+--------------------+-------------+
| id | delivered_on_time | customer_id |
+----+--------------------+-------------+
| 1 | 1 | 9 |
| 2 | 0 | 9 |
| 3 | 1 | 10 |
| 4 | 1 | 10 |
| 5 | 0 | 11 |
+----+--------------------+-------------+
我想获得所有不同的 customer_id,它们的所有订单都已按时交付。 IE。我想要这样的输出:
+-------------+
| customer_id |
+-------------+
| 10 |
+-------------+
最好的方法是什么?
我找到了一个解决方案,但它有点难读,我怀疑这是最有效的方法(使用双 CTE):
> with hits_all as (
select memberid,count(*) as count from orders group by memberid
),
hits_true as
(select memberid,count(*) as count from orders where hit = true group by memberid)
select
*
from
hits_true
inner join
hits_all on
hits_all.memberid = hits_true.memberid
and hits_all.count = hits_true.count;
+----------+-------+----------+-------+
| memberid | count | memberid | count |
+----------+-------+----------+-------+
| 10 | 2 | 10 | 2 |
+----------+-------+----------+-------+
您可以使用聚合和 having
:
select customer_id
from orders
group by customer_id
having min(delivered_on_time) = max(delivered_on_time);
您使用 group by
和 having
如下:
select customer_id
from orders
group by customer_id
having sum(delivered_on_time) = count(*)
之所以有效,是因为 delivered_on_time = 1
确定了准时交货。所以你可以确保 delivered_on_time
的总和等于客户的记录数。
如果 table 中的所有行都符合特定条件,我正在尝试找到一个高性能且易于阅读的查询以从一列中获取不同的值。
我有一个 table 跟踪电子商务订单以及它们是否按时交付、内容和架构如下:
> select * from orders;
+----+--------------------+-------------+
| id | delivered_on_time | customer_id |
+----+--------------------+-------------+
| 1 | 1 | 9 |
| 2 | 0 | 9 |
| 3 | 1 | 10 |
| 4 | 1 | 10 |
| 5 | 0 | 11 |
+----+--------------------+-------------+
我想获得所有不同的 customer_id,它们的所有订单都已按时交付。 IE。我想要这样的输出:
+-------------+
| customer_id |
+-------------+
| 10 |
+-------------+
最好的方法是什么?
我找到了一个解决方案,但它有点难读,我怀疑这是最有效的方法(使用双 CTE):
> with hits_all as (
select memberid,count(*) as count from orders group by memberid
),
hits_true as
(select memberid,count(*) as count from orders where hit = true group by memberid)
select
*
from
hits_true
inner join
hits_all on
hits_all.memberid = hits_true.memberid
and hits_all.count = hits_true.count;
+----------+-------+----------+-------+
| memberid | count | memberid | count |
+----------+-------+----------+-------+
| 10 | 2 | 10 | 2 |
+----------+-------+----------+-------+
您可以使用聚合和 having
:
select customer_id
from orders
group by customer_id
having min(delivered_on_time) = max(delivered_on_time);
您使用 group by
和 having
如下:
select customer_id
from orders
group by customer_id
having sum(delivered_on_time) = count(*)
之所以有效,是因为 delivered_on_time = 1
确定了准时交货。所以你可以确保 delivered_on_time
的总和等于客户的记录数。