我使用以下数据透视表来计算每月的销售额。
mon_pay_amount
用于付款金额。我在tbl_orders
表中还有一个列,其中包含应用的任何折扣mon_order_discount
。
我需要能够将每月的折扣加起来,并将它们从每月的总付款金额中扣除。事后看来,应该在支付表中记录折扣,这可能会使这更容易!
PIVOT
表和销售报告的新手,任何人都知道任何好的教程,到目前为止使用和修改示例已经得到了!!
数据说明
Table Name ID FK Columns
---------------------------------------------------------------------
tbl_orders uid_orders mon_order_discount
tbl_payment uid_payment uid_pay_orderid mon_pay_amount
数据
Data: Jan Feb March
Discounts: 10.00 20.00 10.00
Payments: 200.00 300.00 400.00
结果
Data: Jan Feb March
Totals-Discount: 190.00 280.000 390.00
查询
SELECT *
FROM
(SELECT
DATENAME(month, dte_pay_paydate) mth,
mon_pay_amount
FROM
tbl_payment
INNER JOIN
dbo.tbl_orders ON (uid_pay_orderid = uid_orders)
WHERE
bit_pay_paid = 1
AND txt_pay_descrip <> 'Credit'
AND uid_order_webid = 1
) x
PIVOT
(
SUM(mon_pay_amount)
FOR
mth IN ([January], [February], [March], [April], [May],
[June], [July], [August], September, [October],
[November], [December])
) p
非常感谢
杰森
答案 0 :(得分:1)
您可以在查询中计算正确的金额,类似于:
SELECT *
FROM
(
SELECT
DATENAME(month, p.dte_pay_paydate) mth,
p.mon_pay_amount - o.mon_order_discount as Total
FROM tbl_payment p
INNER JOIN tbl_orders o
ON p.uid_pay_orderid = o.uid_orders
WHERE bit_pay_paid = 1
AND txt_pay_descrip <> 'Credit'
AND uid_order_webid = 1
) x
PIVOT
(
SUM(Total)
FOR
mth IN ([January], [February], [March], [April], [May],
[June], [July], [August], September, [October],
[November], [December])
) p
编辑,根据您的评论,我认为以下内容可能有效:
SELECT *
FROM
(
SELECT DATENAME(month, p.dte_pay_paydate) mth,
sum(p.mon_pay_amount) - TotalDiscByMonth Total
FROM tbl_payment p
INNER JOIN tbl_orders o1
on p.uid_pay_orderid = o1.uid_orders
INNER JOIN
(
select sum(mon_order_discount) TotalDiscByMonth, DATENAME(month, dte_order_stamp) mth
from tbl_orders
group by DATENAME(month, dte_order_stamp)
) o2
ON DATENAME(month, o1.dte_order_stamp) = o2.mth
WHERE bit_pay_paid = 1
AND txt_pay_descrip <> 'Credit'
group by DATENAME(month, p.dte_pay_paydate), TotalDiscByMonth
) x
PIVOT
(
SUM(Total)
FOR
mth IN ([January], [February], [March], [April], [May],
[June], [July], [August], September, [October],
[November], [December])
) p