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(credit) - sum(debits))* 计算 - 时间戳无关紧要
Current_Usage:由 sum(debits) 计算 - 但适用于 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;
4

2 回答 2

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;
于 2012-06-29T17:02:39.973 回答
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

我还没有测试查询。我要说明的重点是如何加入现有查询以获取每月使用量。

于 2012-06-29T05:02:52.430 回答