【发布时间】:2014-08-22 18:04:03
【问题描述】:
我正在尝试将其转换为“毛利”类型的报告,但遇到了问题。
select
CONVERT(VARCHAR(12), ih.invoice_date,110) as invoice_date,
oh.order_no,
bosr.salesrep_name,
bosr.salesrep_id,
oh.location_id,
oh.taker,
oh.customer_id,
Replace(oh.ship2_name, ',', ' ') as Ship_to_name,
bosr.supplier_id,
Replace(bosr.supplier_name, ',', ' ') as Supplier_name,
Cast((dc.dealer_commission_amt_due) as DECIMAL (19,2)) as "Gross Profit"
from oe_hdr oh
inner join anspin_view_booked_orders_ship_to_rep bosr
on oh.order_no = bosr.order_no
inner join oe_line ol
on oh.order_no = ol.order_no
inner join invoice_hdr ih
on oh.order_no = ih.order_no
inner join dealer_commission dc
on ih.invoice_no = dc.invoice_no
where
ih.invoice_date >= '2014-07-01' and
ih.invoice_date < '2014-08-01' and
ol.qty_ordered > '0' and
bosr.source_code_no <> '706' and
bosr.source_code_no <> '709'
group by
CONVERT(VARCHAR(12), ih.invoice_date, 110),
oh.order_no,
bosr.salesrep_name,
bosr.salesrep_id,
oh.location_id,
oh.customer_id,
oh.taker,
oh.ship2_name,
bosr.supplier_id,
bosr.supplier_name,
dc.dealer_commission_amt_due
order by invoice_date;
效果很好,“毛利润”列显示了我想要的日期范围内的正确值......现在,如果我要从组中删除“dc.dealer_commission_amt_due”,然后进行此更改:
Cast(sum(dc.dealer_commission_amt_due) as DECIMAL (19,2)) as "Gross Profit"
我在发票编号的某些(不是全部!这很奇怪,因为有些是正确的)中获得的金额是其原始价值的 2-4+ 倍。
两者之间的示例:
invoice_date order_no salesrep_name salesrep_id location_id taker customer_id Ship_to_name supplier_id Supplier_name Gross Profit
07-10-2014 X NAME ID 60 NAME X Customer INC 123452 supplier INC. 4800.00
非和:
invoice_date order_no salesrep_name salesrep_id location_id taker customer_id Ship_to_name supplier_id Supplier_name Gross Profit
07-10-2014 X NAME ID 60 NAME X Customer INC 123452 supplier INC. 750.00
invoice_date order_no salesrep_name salesrep_id location_id taker customer_id Ship_to_name supplier_id Supplier_name Gross Profit
07-10-2014 X NAME ID 60 NAME X Customer INC 123452 supplier INC. 450.00
从我读到的内容来看,这与连接有关...这是正确的吗?
【问题讨论】:
-
I
m guessing its 由于粒度不同,您必须在子查询中使用 group by 和 JOIN 来获得总和。 -
您的连接会产生意外的行数。对总数不正确的其中一张发票运行不聚合查询。您会看到额外的行。
标签: sql sql-server sql-server-2008 sum inner-join