[英]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.