[英]Select / group by multiple columns but count just the values of one column
我有2张桌子。
表#1:订单
order_id | crit_1 | crit_2 | crit_3 | other
01 | A00 | GER | 49er | x
02 | A00 | GER | 49er | x
03 | A00 | USA | 49er | x
04 | C80 | DEN | 66er | x
05 | B50 | GER | 99er | x
表格orders
具有3个重要条件,但不具有criterion_4
。 还有另一个带有order_positions
表,其中每个order_id
包含多个criterion_4
条目。
表#2:分类
crit_1 | crit_2 | crit_3 | crit_4 | class_1 | class_2
A00 | GER | 49er | 4711 | A | 11
A00 | GER | 49er | 4712 | A | 21
A00 | USA | 49er | 4711 | D | 12
A00 | USA | 49er | 4712 | D | 21
B50 | GER | 99er | 4801 | B | 12
B50 | GER | 99er | 4802 | B | 12
B50 | GER | 99er | 4803 | B | 14
C80 | DEN | 66er | 4904 | C | 22
C80 | DEN | 66er | 4905 | C | 21
表格classifications
包含以下分类:
orders = class_1 = combination of crit_1, crit_2 & crit_3
order_positions = class_2 = combination of crit_1, crit_2, crit_3 & crit_4
我有一个查询,在其中我在表orders
上加入classifications.class_1
,以创建所有orders
及其各自classification
的列表。
select
orders.order_id,
orders.crit_1,
orders.crit_2,
orders.crit_3,
classifications.class_1
from
orders
left join
classifications
on
orders.crit_1=classifications.crit_1 and
orders.crit_2=classifications.crit_2 and
orders.crit_3=classifications.crit_3
where
orders.others = "..."
group by
orders.order_id,
orders.crit_1,
orders.crit_2,
orders.crit_3,
classifications.class_1
最后,我需要一个GROUP BY,因为表分类包含多个条目,其中包含crit_1
, crit_2
和crit_3
的组合。 但由于所需的,这是没有问题的classification_1
总是对的每个组合相同crit_1, crit_2
和crit_3
。
现在,我想创建另一个查询,在该查询中我仅计算订单的每个classification_1
_1的数量。 像这样:
class_1 | number
A | 12
B | 5
C | 18
. | .
但是我不知道没有全部选择的orders.order_id, orders.crit_1
, orders.crit_2
, orders.crit_3
和classifications.class_1
我只想计算上面查询的class_1
分类。
有什么建议么?
编辑
我像考希克·纳亚克(Kaushik Nayak)建议的那样尝试了它:
select
--orders.order_id,
--orders.crit_1,
--orders.crit_2,
--orders.crit_3,
classifications.class_1,
count(*)
from
orders
left join
classifications
on
orders.crit_1=classifications.crit_1 and
orders.crit_2=classifications.crit_2 and
orders.crit_3=classifications.crit_3
where
orders.others = "..."
group by
--orders.order_id,
--orders.crit_1,
--orders.crit_2,
--orders.crit_3,
classifications.class_1
但是结果不正确,我也不知道如何重现这些数字。
一些例子:
| class_1 | query w/ | query w/o | query |
| | group by | group by | count(*) |
---------------------------------------------
| A | 654 | 2179 | 1024 |
| B | 371 | 1940 | 667 |
| C | 94 | 238 | 247 |
当我对group by
使用查询时,我会收到654个class_1
= A的条目。当我对group by
不进行查询时group by
我会得到2179 class_1
= A的条目。当我尝试使用Count(*)
查询时,我得到了class_1
= A的1024个条目。
最后一个绝对不正确。
只需对您的classifications
表使用GROUP BY
class_1并添加EXISTS
条件以检查是否有订单。
SELECT
c.class_1,
COUNT(c.class_1) "number"
FROM
classifications c
WHERE
EXISTS (
SELECT
1
FROM
orders o
WHERE
o.crit_1 = c.crit_1
AND o.crit_2 = c.crit_2
AND o.crit_3 = c.crit_3
)
GROUP BY
c.class_1
ORDER BY
1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.