任何人都可以帮我修复这个SQL查询。我正在返回有在线收银员的等待客户数量。一些收银员没有任何Waiting_Customer
因此在结果中不可见。我的必需输出也是显示出纳的0 Waiting_Customer
,如下所示。
POS Waiting_Customer
1 0
2 0
3 0
4 11
当它使用下面的查询返回以下结果时。
Select TOP 10
posId as 'POS',
count(number) As 'Waiting_Customer'
From
Tickets
Where
(PosId = 1 or PosId = 2 or PosId = 3 or PosId = 4)
and PosId between 1 and 12
and Status = 1 isTaken=1
Group by
PosId
Order by
Count(number)
输出:
POS Waiting_Customer
4 11
查询:
select distinct(cgroup)
from Pos
where status = 1 and id between 1 and 12
输出:
cgroup
1
2
3
4
查询:
select top 100 *
from Tickets
where Status = 1
and isTaken = 1
and PosId IN (1, 2, 3, 4)
and PosId BETWEEN 1 and 12
order by
id desc
输出:
Id PosId Status Number isTaken
7596 4 1 734 1
7594 1 1 732 1
7591 1 1 729 1
7588 3 1 726 1
7587 2 1 725 1
答案 0 :(得分:3)
使用包含原始WHERE
子句中逻辑的条件聚合:
SELECT PosId as 'POS',
SUM(CASE WHEN PosId BETWEEN 1 AND 12 AND Status = 1 AND isTaken = 1
THEN 1 ELSE 0 END) AS Waiting_Customer
FROM Tickets
GROUP BY PosId
ORDER BY Waiting_Customer
答案 1 :(得分:0)
这些解决方案为pos 1到4生成记录,因此即使你的表为空,也会返回4行
with r (n) as (select 1 union all select n+1 from r where n<4)
select r.n as pos
,coalesce (Waiting_Customer,0) as Waiting_Customer
from r
left join (select posId
,count(number) as Waiting_Customer
From Tickets
Where PosId between 1 and 4
and Status=1
and isTaken=1
Group by PosId
) t
on t.posId = r.n
Order by Waiting_Customer
;
选项2
select r.n as pos
,coalesce (Waiting_Customer,0) as Waiting_Customer
from (values (1),(2),(3),(4)) r(n)
left join (select posId
,count(number) as Waiting_Customer
From Tickets
Where PosId between 1 and 4
and Status=1
and isTaken=1
Group by PosId
) t
on t.posId = r.n
Order by Waiting_Customer
;