子查询未产生预期结果(SELECT DISTINCT和COUNT)

时间:2017-05-11 12:17:06

标签: sql subquery

我的查询是:

SELECT distinct d.Z4BSN2,
  (SELECT COUNT(Z4RMID) 
   FROM ZWE944 as d1 
   where d1.Z4RMID = d.Z4RMID 
    and d1.Z4BSN2 = d.Z4BSN2 )
FROM ZWE944 as d
WHERE Z4RYMD = 170505

来源数据:

Z4RMID              Z4BSN2      Z4PONO  Z4ITNO      Z4RYMD  Z4RHMS  Z4USER
C17D29014A          801464552   MWV TO  2038284     170505  170103  CNVTST
C87D25211C          801462997   MWV TO  2038292     170505  170103  CNVTST
C87D25273D          801462997   MWV TO  2038292     170505  170103  CNVTST
C87D25281D          801462997   MWV TO  2038292     170505  170103  CNVTST
C87D25282Z          801462997   MWV TO  2038292     170505  170103  CNVTST

我期待2行,计数为1和5.然而,这两行都给我一个计数1.我无法弄清楚我哪里出错了。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

提供别人说的是真的(你应该添加样本数据和预期的输出),你似乎不需要那个内部查询,你可以实现与

相同
select  Z4BSN2,
        count(Z4RMID) 
from    ZWE944
where   Z4RYMD = 170505
group by Z4BSN2

答案 1 :(得分:1)

鉴于您的样本数据,您只需要计数1和1,因为Z4RMID是不同的,这意味着您的内部选择在Z4RMID上的位置只会选择一条记录。

删除第一个得到你想要的地方,例如:

declare @zwe944 table
(
Z4RMID varchar(10),
Z4BSN2 varchar(10),
Z4PONO varchar(10),
Z4ITNO int,
Z4RYMD int,
Z4RHMS int,
Z4User varchar(10) 
)

INSERT INTO @zwe944 VALUES ('C17D29014A',801464552,'MWV TO',2038284,170505,170103,'CNVTST')
INSERT INTO @zwe944 VALUES ('C87D25211C',801462997,'MWV TO',2038292,170505,170103,'CNVTST')
INSERT INTO @zwe944 VALUES ('C87D25273D',801462997,'MWV TO',2038292,170505,170103,'CNVTST')
INSERT INTO @zwe944 VALUES ('C87D25281D',801462997,'MWV TO',2038292,170505,170103,'CNVTST')
INSERT INTO @zwe944 VALUES ('C87D25282Z',801462997,'MWV TO',2038292,170505,170103,'CNVTST')


SELECT distinct d.Z4BSN2,
  (SELECT COUNT(Z4RMID) 
   FROM @ZWE944 as d1 
   where d1.Z4RMID = d.Z4RMID 
    and d1.Z4BSN2 = d.Z4BSN2 )
   FROM @ZWE944 as d
    WHERE Z4RYMD = 170505

SELECT distinct d.Z4BSN2,
  (SELECT COUNT(Z4RMID) 
   FROM @ZWE944 as d1 
   where d1.Z4BSN2 = d.Z4BSN2 )
FROM @ZWE944 as d
WHERE Z4RYMD = 170505

第二个查询给出了1和4的计数,但这对数据是正确的。