嵌套查询&交易

时间:2012-06-29 04:50:18

标签: mysql nested-queries nested-query

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

余额:按(总和(信用) - 总和(借方))计算* - 时间戳无关紧要
Current_Usage:以sum(借记)计算 - 但用于JUN中的借记。

问题:如果我立即按JUN时间戳过滤,它不计算所有时间的余额,而只计算6月份任何交易的余额。

如何按月计算当前使用量,但是表中所有交易的余额。我有一切正常,除了它只将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;

2 个答案:

答案 0 :(得分: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

我没有测试过查询。我想说的是你如何加入现有的查询以获得每月的使用量。

答案 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;