时间:2015-05-13 20:14:18

标签: sql sql-server

我有以下的sql。如果布尔值被选中0,我希望我的结果被分组,但是如果检查布尔值则不分组1.下面的代码是一个好方法吗?我觉得它应该工作,但它抛出错误“InvoicePeriodID在选择列表中无效,因为它不包含在aggraagt​​e函数或组中”任何建议?

----insert invoices for rebates grouped by date, address, contract, rebate note, and order type
declare @invoices table(InvoicePeriodID int, InvoiceStartDate datetime, InvoiceEndDate datetime, JDEAddressNo float, ContractID int, RebateNoteID int, JDEOrderType char(2), RebateInvoiceID int)
insert @invoices (InvoicePeriodID , InvoiceStartDate , InvoiceEndDate , JDEAddressNo , ContractID , RebateNoteID, JDEOrderType)
select
  i.InvoicePeriodID
, i.InvoiceStartDate
, i.InvoiceEndDate
, i.JDEAddressNo
, i.ContractID
, i.RebateNoteID
, i.JDEOrderType
from 
  @inv i
group by
  case i.InvoiceSeparately
    when 1 then null
    when 0 then i.InvoicePeriodID
  end
, case i.InvoiceSeparately
    when 1 then null
    when 0 then i.InvoiceStartDate
  end
, case i.InvoiceSeparately
    when 1 then null
    when 0 then i.InvoiceEndDate
  end 
, case i.InvoiceSeparately
    when 1 then null
    when 0 then i.JDEAddressNo
  end
, case i.InvoiceSeparately
    when 1 then null
    when 0 then i.ContractID
  end 
, case i.InvoiceSeparately
    when 1 then null
    when 0 then i.RebateNoteId
  end
, case i.InvoiceSeparately
    when 1 then null
    when 0 then i.JDEOrderType
  end

1 个答案:

答案 0 :(得分:1)

我认为以这种方式做你想要的更容易阅读和更容易

select
  i.InvoicePeriodID
, i.InvoiceStartDate
, i.InvoiceEndDate
, i.JDEAddressNo
, i.ContractID
, i.RebateNoteID
, i.JDEOrderType
from 
  @inv i
WHERE i.InvoiceSeparately = 0
group BY  i.InvoicePeriodID

 ,i.InvoiceStartDate
   ,i.InvoiceEndDate
  , i.JDEAddressNo
 , i.ContractID
  ,i.RebateNoteId
 , i.JDEOrderType
 UNION ALL 
 select
  i.InvoicePeriodID
, i.InvoiceStartDate
, i.InvoiceEndDate
, i.JDEAddressNo
, i.ContractID
, i.RebateNoteID
, i.JDEOrderType
from 
  @inv i
WHERE i.InvoiceSeparately = 1