sql高手请进,sql出现怪事 (200分)

  • 主题发起人 主题发起人 handsome1234
  • 开始时间 开始时间
H

handsome1234

Unregistered / Unconfirmed
GUEST, unregistred user!
ckls出库历史
FA A2 A8
1 素围巾 10
2 V领男套衫 10
3 V领抽条男套背心 10
4 扇贝网眼围巾 10
5 超薄精纺纯绒披肩 10
6 小八字领长袖明门平摆女衬衫 10
7 大八字领长袖明门圆摆女衬衫 20
8 自带领翻花半袖女套衫 20
9 大圆领抽条女套衫 20
10 V领半袖男套衫 6
11 自带领翻花半袖女套衫 19
12 超薄精纺纯绒披肩 10
13 素围巾 10
14 V领男套衫 10
15 扇贝网眼围巾 2
16 V领抽条男套背心 1


xsls 销售历史
FA A2 A8
1 V领半袖男套衫 6
2 自带领翻花半袖女套衫 20
3 超薄精纺纯绒披肩 10
4 素围巾 10
5 V领男套衫 10
6 V领抽条男套背心 1
7 扇贝网眼围巾 2


Select A.A2 As PM,Sum(A.A8) As CK,Sum(B.A8) As XS
From CKLS As A Left Join XSLS As B
On (A.A2=B.A2) And (A.A8=B.A8)
Group By A.A2
问题一:执行完语句后 xs这一列 数据就不对,
pm ck xs
1 V领半袖男套衫 6 6
2 V领抽条男套背心 11 1
3 V领男套衫 20 20
4 超薄精纺纯绒披肩 20 20
5 大八字领长袖明门圆摆女衬衫 20 空
6 大圆领抽条女套衫 20 空
7 扇贝网眼围巾 12 2
8 素围巾 20 20
9 小八字领长袖明门平摆女衬衫 10 空
10 自带领翻花半袖女套衫 39 20


///////////////////////////////////////////////////////////////
如果执行这一句,结果更可怕:

Select A.A2 As PM,Sum(A.A8) As CK,Sum(B.A8) As XS
From CKLS As A Left Join XSLS As B
On (A.A2=B.A2) { 如果少了这句 And (A.A8=B.A8) }
Group By A.A2
pm ck xs
1 V领半袖男套衫 6 6
2 V领抽条男套背心 11 2 //这里有点变化1--》2
3 V领男套衫 20 20
4 超薄精纺纯绒披肩 20 20
5 大八字领长袖明门圆摆女衬衫 20 空
6 大圆领抽条女套衫 20 空
7 扇贝网眼围巾 12 4 //这里有点变化2--》4
8 素围巾 20 20
9 小八字领长袖明门平摆女衬衫 10 空
10 自带领翻花半袖女套衫 39 40 //这里有点变化20--》40


问题二:我标记的为什么会有变化


请问各位:这里的sql语句执行出来的怎么是这样的呢?



 
我想要得到的,大家从sql中可以看出来:
以出库为基准,把出库和销售同名的货物作个统计sum()
那位高手可以给出sql也可以,
 
这样试一下:
select c.pm,sum(c.ck) ck,sum(c.xs) xs from (select a.a2 as pm,a.a8 ck,b.a8 xs
From CKLS As A Left Join XSLS As B on a.a2=b.a2) c group by c.pm
 
你B表里的数据被累加了A表重复的次数,这样通常是你的条件引起的,
修改一下就成了。
 
这样试一试:
Select A.A2 As PM,Sum(A.A8) As CK,Sum(B.A8) As XS
From CKLS As A Left Join XSLS As B
On (A.A2=B.A2)
Group By A.A2
HAVING Sum(A.A8)=Sum(B.A8)
 
select ckt.a2,ckt.ck,xst.xs from
(select A2,ck=sum(A8)
from ckls
group by A2) ckt left join
(select A2,xs=sum(A8)
from xsls
group by A2) xst on ckt.a2=xst.a2
 
问题解决了:
declare @B table
(A2 char(30),A8 int)
insert into @B(A2,A8) Select A2,Sum(A8) From Table2 Group By A2

Select B.A2 as Pm,Sum(A.A8) as CK,B.A8 as CX from @B as B
join Table1 as A
on B.A2=A.A2
Group By B.A2,B.A8
这样可以把出库表和销售表进行统计
在最后加一句
Having B.A8=Sum(A.A8)
则只显示出库表和销售表中统计数据相同的项
 
我更改后的代码:
select a.a2 as pm ,a.ck ,b.xs
from (select a2,sum(a8) as ck
from ckls group by a2) a left join
(select a2,sum(a8) as xs
from xsls group by xsls.a2 ) b on a.a2=b.a2
 
多人接受答案了。
 
后退
顶部