【问题标题】:How to get the value returned by count in Select statement如何在Select语句中获取count返回的值
【发布时间】:2014-03-26 03:44:59
【问题描述】:

我有以下 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 子句来计算行数,但我真的更希望得到 count() invoices 值。

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

感谢您的帮助。 西蒙

【问题讨论】:

    标签: sql sql-server-2008 select group-by sql-server-2012


    【解决方案1】:

    将值放入变量中。像这样的:

    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
    

    【讨论】:

    • 为变量赋值的选择语句不得与数据检索操作结合使用
    • @Shimon 我忘记了发票 ID。试试我更新的答案。
    【解决方案2】:

    查询中的用例语句

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多