更新#1:查詢給我的語法錯誤的左連接線(運行左內聯接的查詢獨立完美的作品雖然)嵌套查詢及交易
SELECT b1.company_id, ((sum(b1.credit)-sum(b1.debit)) as 'Balance'
FROM MyTable b1
JOIN CustomerInfoTable c on c.id = b1.company_id
#Filter for Clients of particular brand, package and active status
where c.brand_id = 2 and c.status = 2 and c.package_id = 3
LEFT JOIN
(
SELECT b2.company_id, sum(b2.debit) as 'Current_Usage'
FROM MyTable b2
WHERE year(b2.timestamp) = '2012' and month(b2.timestamp) = '06'
GROUP BY b2.company_id
)
b3 on b3.company_id = b1.company_id
group by b1.company_id;
原貼:
我跟蹤同一張表中的借方和貸方。該表具有以下模式:
| company_id | timestamp | credit | debit |
| 10 | MAY-25 | 100 | 000 |
| 11 | MAY-25 | 000 | 054 |
| 10 | MAY-28 | 000 | 040 |
| 12 | JUN-01 | 100 | 000 |
| 10 | JUN-25 | 150 | 000 |
| 10 | JUN-25 | 000 | 025 |
至於我的結果,我想看到:
| Grouped by: company_id | Balance* | Current_Usage (in June) |
| 10 | 185 | 25 |
| 12 | 100 | 0 |
| 11 | -54 | 0 |
餘額:通過計算(SUM(信用) - 和(借方))* - 時間戳沒有關係
Current_Usage:通過總和(借方)計算 - 但只有在JUN中借記。
問題:如果我馬上通過JUN時間戳進行篩選,它不會計算所有時間的餘額,而只會計算六月份任何交易的餘額。
我該如何計算按月份的當前使用情況,而如何計算表格中所有交易的餘額。我所擁有的一切工作,但它過濾只有JUN結果到我的代碼當前使用情況計算:
SELECT b.company_id, ((sum(b.credit)-sum(b.debit))/1024/1024/1024/1024) as 'BW_remaining', sum(b.debit/1024/1024/1024/1024/28*30) as 'Usage_per_month'
FROM mytable b
#How to filter this only for the current_usage calculation?
WHERE month(a.timestamp) = 'JUN' and a.credit = 0
#Group by company in order to sum all entries for balance
group by b.company_id
order by b.balance desc;
我在左連接中出現語法錯誤。如果我只在聯接中運行查詢,它會很好地運行: 我運行以下查詢: ### update:在註釋中很難對代碼進行格式設置,因此我更新了Update# 1 –