1

我正在使用以下查询来获取一些销售数据。问题是它返回了错误的数据。

我将三张桌子连接在一起tbl_orders tbl_orderitems tbl_payment。该tbl_orders表保存摘要信息,tbl_orderitems保存订购的项目,该tbl_payment表保存有关订单的付款信息。可以针对每个订单进行多次付款。

我正在尝试获取物品的总和sum(mon_orditems_pprice),以及所售物品的数量count(uid_orderitems)

当我针对特定订单号运行以下查询时,我知道该订单号有 1 个订单项。它返回计数 2 和两项之和。

Item                       ProdTotal    ProdCount
Westvale Climbing Frame    1198         2

此订单在tbl_payment表中保存了两条付款记录,导致重复计数。如果我删除付款表加入,它会报告正确的数字,或者如果我选择一个具有单笔付款的订单,它也可以工作。我是不是错过了什么,我累了!??

SELECT 
  txt_orditems_pname,
  SUM(mon_orditems_pprice) AS prodTotal,
  COUNT(uid_orderitems) AS prodCount
FROM dbo.tbl_orders
  INNER JOIN dbo.tbl_orderitems ON (dbo.tbl_orders.uid_orders = dbo.tbl_orderitems.uid_orditems_orderid)
  INNER JOIN dbo.tbl_payment ON (dbo.tbl_orders.uid_orders = dbo.tbl_payment.uid_pay_orderid)
WHERE
  uid_orditems_orderid = 61571
GROUP BY
  dbo.tbl_orderitems.txt_orditems_pname
ORDER BY
  dbo.tbl_orderitems.txt_orditems_pname

有什么建议么?

谢谢你。

向下钻取表列

dbo.tbl_payment.bit_pay_paid (1/0) Has this payment been paid, yes no
dbo.tbl_orders.bit_order_archive (1/0) Is this order archived, yes no
dbo.tbl_orders.uid_order_webid (integer) Web Shop's ID
dbo.tbl_orders.bit_order_preorder (1/0) Is this a pre-order, yes no
YEAR(dbo.tbl_orders.dte_order_stamp) (2012) Sales year
dbo.tbl_orders.txt_order_status (varchar) Is the order dispatched, awaiting delivery
dbo.tbl_orderitems.uid_orditems_pcatid (integer) Product category ID
4

1 回答 1

1

这是正常行为,如果您删除分组子句,您会看到加入后确实有 2 行,并且它们都有 599 作为 amon_orditems_pprice因此SUM是正确的。当任何连接表中存在多重匹配时,整个输出行将变为多重,并且正在求和(或以任何其他方式计算或聚合)的数据也将多次求和。试试这个:

SELECT      txt_orditems_pname,
            SUM(mon_orditems_pprice) AS prodTotal,
            COUNT(uid_orderitems) AS prodCount
FROM        dbo.tbl_orders
INNER JOIN  dbo.tbl_orderitems ON (dbo.tbl_orders.uid_orders = dbo.tbl_orderitems.uid_orditems_orderid)
INNER JOIN  
(
    SELECT  x.uid_pay_orderid
    FROM    dbo.tbl_payment x
    GROUP   BY x.uid_pay_orderid
) AS payments ON (dbo.tbl_orders.uid_orders = payments.uid_pay_orderid)

WHERE
  uid_orditems_orderid = 61571
GROUP BY
  dbo.tbl_orderitems.txt_orditems_pname
ORDER BY
  dbo.tbl_orderitems.txt_orditems_pname

我不知道tbl_payment您使用的是什么数据,SELECT 列表中的任何列实际上来自tbl_payment吗?为什么tbl_payment被加入?

于 2012-11-28T15:04:32.830 回答