加入SQL Server 2008的表问题

时间:2012-11-28 14:50:08

标签: sql sql-server-2008

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

我正在加入三个表tbl_orders tbl_orderitems tbl_paymenttbl_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

1 个答案:

答案 0 :(得分:1)

这是一种正常的行为,如果删除分组子句,您会看到加入后确实有2行,并且它们都有599作为mon_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被加入?