Sql 如何在Select语句中获取count返回的值
我有以下sql查询:Sql 如何在Select语句中获取count返回的值,sql,sql-server-2008,select,group-by,sql-server-2012,Sql,Sql Server 2008,Select,Group By,Sql Server 2012,我有以下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()发票,但是我似乎无法找到获得该值的方法。我知道我可以通过删除GROUPBY子句来进行行计数,但我更希望得到count()值 Select Invoice
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()发票,但是我似乎无法找到获得该值的方法。我知道我可以通过删除GROUPBY子句来进行行计数,但我更希望得到count()值
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
谢谢你的帮助。
Shimon将值放入变量中。大概是这样的:
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
查询中的用例语句
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
为变量赋值的select语句不得与数据检索结合使用operations@Shimon我忘记了发票id。请尝试我的更新答案。