1

我正在使用以下数据透视表来计算每月的销售额。

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

非常感谢

杰森

4

1 回答 1

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

请参阅带有演示的 SQL Fiddle

于 2012-11-30T11:17:34.443 回答