我使用子查询返回两个日期之间的平均金额和总金额,当返回平均金额时,我必须使用子查询中的选定列。
以下是我试过的。
tbl_batch_charges
merchant_id total_transaction_amount settlement_date
1 33.65 2014-07-01
1 33.65 2014-07-10
2 39.36 2014-07-15
merchant_application_form
merchant_id active_date
1 2013-10-20
2 2014-01-10
Resulted Table
merchant_id weekly_transaction total_turnover
1 xx 67.3
2 xx 39.36
select tbl_batch.merchant_id,
tbl_merchant.merchant_application_form_active_date,
GETDATE() as today_date,
(select sum(tbl_batch.total_transactions_amount) from Borgun.dbo.tbl_batch_charges as tbl_batch
where tbl_batch.settlement_borgun_date between '2014-07-01' and '2014-10-20' and
tbl_batch.merchant_id='9947230') as weekly_total_amount,
(select (sum(tbl_batch.total_transactions_amount)/(ceiling(convert(float, abs(datediff(day, active_date, today_date)))/7)))) as total_turn_over
from Borgun.dbo.tbl_batch_charges as tbl_batch
left join Borgun.dbo.tbl_merchant_application_form as tbl_merchant on tbl_merchant.merchant_application_form_merchant_id=tbl_batch.merchant_id
where tbl_batch.merchant_id='9947230' group by tbl_batch.merchant_id;
**我希望商家从他加入的日期开始每周平均转换到当前日期。 **
请告诉我如何在sql server中解决这个问题。
提前致谢。
答案 0 :(得分:0)
我不明白您的问题是什么,但将代码重写为以下语法可能有效
SELECT
tbl_batch.merchant_id,
tbl_merchant.merchant_application_form_active_date,
GETDATE() AS today_date,
sum(tbl_batch.total_transactions_amount) as total_amount,
avg(tbl_batch.total_transactions_amount) as average_amount
FROM
Borgun.dbo.tbl_batch_charges tbl_batch
LEFT JOIN Borgun.dbo.tbl_merchant_application_form tbl_merchant on tbl_batch.merchant_id = tbl_merchant.merchant_application_form_merchant_id
WHERE
Settlement_borgun_date between '2014-07-01' and '2014-10-20'
and tbl_batch.merchant_id='9947230'
GROUP BY
tbl_batch.merchant_id,
tbl_merchant.merchant_application_form_active_date
答案 1 :(得分:0)
请试试这个
SELECT
tbl_batch.merchant_id,
total_turnover = AVG(tbl_batch.total_transactions_amount),
weekly_transaction = SUM(tbl_batch.total_transactions_amount)
FROM Borgun.dbo.tbl_batch_charges as tbl_batch
LEFT JOIN Borgun.dbo.tbl_merchant_application_form as tbl_merchant
ON tbl_merchant.merchant_application_form_merchant_id=tbl_batch.merchant_id
WHERE tbl_batch.merchant_id='9947230'
AND tbl_batch.settlement_borgun_date between '2014-07-01' and '2014-10-20'
GROUP BY tbl_batch.merchant_id,
tbl_merchant.merchant_application_form_active_date