我执行的查询似乎忽略了子查询中的where子句 (从b.amazon = 2和manifest = a.dbid的订单中选择计数(亚马逊)
列亚马逊是INT类型 SQL SERVER 2014
如果我自己运行查询并输入清单值,我会得到正确的结果,我期待并且是1
从亚马逊= 2和清单=' 211104'的订单中选择计数(亚马逊) 结果返回1
当我运行下面的查询时,我得到的结果为5,即清单= 211104的所有订单的计数,但亚马逊的值在4个结果中为1,结果为2个。
Select distinct
top 30 DBID, today ,sum([amazon-orders])
From
(
SELECT [dbid], [today],
(select count(amazon) from orders
where b.amazon = 2 and manifest = a.dbid) as [amazon-orders]
FROM [manifest] a
join orders b on a.[dbid] = b.[manifest]
) t1
Group By
DBID, today
order by dbid desc
有人可以帮帮我吗。
由于
答案 0 :(得分:1)
你有一个额外的连接,所以你多次计数......这样做:
Select distinct
top 30 DBID, today ,sum([amazon-orders])
From
(
SELECT [dbid], [today],
(select count(amazon) from orders b
where b.amazon = 2 and manifest = a.dbid) as [amazon-orders]
FROM [manifest] a
) t1
Group By
DBID, today
order by dbid desc
或者像这样
SELECT [dbid], [today], count(o.amazon)
FROM [manifest] a
join orders o on a.dbid = o.manifest and o.amazon = 2
group by dbid, today
或者如果你有不想加入的列(在你的查询中只有这一个连接,你需要使用左连接):
SELECT [dbid], [today], sum(case when o.amazon is not null then 1 else 0 end)
FROM [manifest] a
left join orders o on a.dbid = o.manifest and o.amazon = 2
group by dbid, today
答案 1 :(得分:0)
这是怎么回事?
SELECT top 30 [dbid], [today], sum(case when b.amazon = 2 then 1 else 0 end) as [amazon-orders]
FROM [manifest] a
join orders b on a.[dbid] = b.[manifest]
group by DBID, today
order by dbid desc
非常确定,因为您的查询实际上连接了两次订单,所以增加了计数。
答案 2 :(得分:0)
使用此:
select a.DBID, a.today, count(b.amazon) from [manifest] a
join orders b on a.[dbid] = b.[manifest] and b.amazon = 2
Group By a.DBID, a.today