我有以下sql查询:
Select Invoices.ID, count(*) invoices
From
Customers.ID F
Inner join Invoices p
On P.ID=F.ID and f.ID = 1
group by p.ID
GO
我想要做的是在p.ID组后面的if语句中使用count()个发票,但是我似乎无法找到获取该值的方法。我知道我可以通过删除group by子句来进行行计数,但我更愿意得到计数()发票的值。
Select Invoices.ID, count(*) invoices
From
Customers.ID F
Inner join Invoices p
On P.ID=F.ID and f.ID = 1
group by p.ID
if ("value from count(*) invoices) = 0
do some stuff here
else
do some other stuff here
GO
谢谢你的帮助。 希蒙
答案 0 :(得分:0)
将值放在变量中。像这样:
declare @invoice_id int;
declare @myCount int;
Select @invoice_id = Invoices.ID, @myCount = count(*)
From
Customers.ID F
Inner join Invoices p
On P.ID=F.ID and f.ID = 1
group by p.ID
if (@myCount) = 0
do some stuff here
else
do some other stuff here
GO
答案 1 :(得分:0)
在查询中使用Case语句
Select Invoices.ID,
Case When count(*)=0
then "do something"
else "do something" end AS invoices
From
Customers.ID F
Inner join Invoices p
On P.ID=F.ID and f.ID = 1
group by p.ID
GO