我正在嘗試將資料倉庫中的資料匯總到一個事實表中,并且我希望能夠計算每個客戶每月每種型別的交易數量。
使用的列是:Customer_id、Transaction_id、transaction_date、Transaction_type
理想情況下,我想要得到的是。
| 顧客 | 月 | 交易型別_1 | 交易型別_2 | Total_transactions |
|---|---|---|---|---|
| 12345 | 1 | 18 | 8 | 26 |
| 12345 | 2 | 23 | 14 | 37 |
| 67891 | 1 | 14 | 22 | 36 |
我必須把它放到一個子查詢中,但我得到了每個月所有客戶的型別 1 交易的總數。我曾嘗試在此基礎上使用磁區但沒有成功,但現在遠遠超出了我的水平。
Select
customer_id,
month,
count(transactions_id),
(select count(transactions_id) from DWH where transaction_type = 1),
(select count(transactions_id) from DWH where transaction_type = 2)
FROM DWH
GROUP BY customer_id, month
不正確的表輸出看起來像這樣。
| 顧客 | 月 | 交易型別_1 | 交易型別_2 | Total_transactions |
|---|---|---|---|---|
| 12345 | 1 | 432 | 564 | 26 |
| 12345 | 2 | 456 | 765 | 37 |
在獨立表中,我可以獲得資訊,但無法將其合并到事實表視圖中。
獨立這可以獲取每種型別的單獨計數,但我無法將其重新處理為選擇子查詢:
select customer_id, month, count(*)
FROM DWH
WHERE dwh.transaction_type = 1
Group BY dwh.customer_id, month;
任何幫助將非常感激。
uj5u.com熱心網友回復:
您可能會得到不正確的結果,因為您各自子查詢的 where 子句中的過濾器不考慮按列分組,即
表別名d幫助我們區分外部/通用查詢和子查詢中使用的列。
select
d.customer_id,
d.month,
count(d.transactions_id),
(
select count(transactions_id)
from DWH
where transaction_type = 1 and
customer_id = d.customer_id and
month = d.month
) as transaction_type_1,
(
select count(transactions_id)
from DWH
where transaction_type = 2 and
customer_id = d.customer_id and
month = d.month
) as transaction_type_2
FROM DWH d
GROUP BY d.customer_id, d.month
然而,雖然這種方法可能有效,但最好在各自的資料庫上測驗這種性能并評估成本指標/查詢計劃。
另一種可能是高性能的方法使用 case 運算式來實作結果,并已包含在下面:
SELECT
customer_id as Customer,
month,
COUNT(
CASE WHEN transaction_type=1 THEN transactions_id END
) as transaction_type_1,
COUNT(
CASE WHEN transaction_type=2 THEN transactions_id END
) as transaction_type_2,
COUNT(1) as Total_transactions
FROM
DWH
GROUP BY
customer_id, month
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354055.html
上一篇:SQL查詢-根據條件顯示常見行
