2012-06-29 72 views
0

更新#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; 

回答

0

你需要在這裏是將過濾器的基礎上每月子查詢中使用聯接。

SELECT T1.company_id, 
     ((sum(T1.credit)-sum(T1.debit))/1024/1024/1024/1024) as 'BW_remaining', 
     MAX(T3.DEBIT_PER_MONTH) 
FROM MYTABLE T1 
LEFT JOIN 
(
    SELECT T2.company_id, SUM(T2.debit) T3.DEBIT_PER_MONTH 
    FROM MYTABLE T2 
    WHERE month(T2.timestamp) = 'JUN' 
    GROUP BY T2.company_id 
) 
T3 ON T1.company_id-T3.company_id 
GROUP BY T1.company_id 

我還沒有測試過這個查詢。在這裏我試圖做的是如何加入你現有的查詢來獲得每月使用量。

+0

我在左連接中出現語法錯誤。如果我只在聯接中運行查詢,它會很好地運行: 我運行以下查詢: ### update:在註釋中很難對代碼進行格式設置,因此我更新了Update# 1 –

0

好吧,感謝@Kshitij我得到了它的工作。如果有人遇到同樣的問題,這就是我解決它的方法:

SELECT b1.company_id, ((sum(b1.credit)-sum(b1.debit)) as 'Balance', 
    (
    SELECT sum(b2.debit) 
    FROM MYTABLE b2 
    WHERE b2.company_id = b1.company_id and year(b2.timestamp) = '2012' and month(b2.timestamp) = '06' 
    GROUP BY b2.company_id 
) AS 'Usage_June' 

FROM MYTABLE b1 

#Group by company in order to add sum of all zones the company is using 
group by b1.company_id 
order by Usage_June desc;