【问题标题】:Selecting multiple rows into a single row temp table将多行选择到单行临时表中
【发布时间】:2013-10-24 14:59:54
【问题描述】:

我想要做的是将多行选择到临时表的单行中。临时表中应该有 1 行列出所有不同的应计值。下面是代码:

    declare @RunDate varchar(7)
set @RunDate = '2013-07'

declare @ShortItemNo1 int

set @ShortItemNo1 = 723639




declare @SalesAccruals table(QuantityShipped int, ShortItemNo int, GrossAmount money, AccrualReturns money, AccrualMedicaid money,
                            AccrualChargebacks money)

insert @SalesAccruals

select
    sum(s.QuantityShipped) QuantityShipped,
    s.ShortItemNo,
    sum(s.ExtendedPrice) ExtendedPrice,
    case when aa.AccrualType=3 then sum(a.AccrualAmount) end,
    case when aa.AccrualType=8 then sum(a.AccrualAmount) end,
    case when aa.AccrualType=2 then sum(a.AccrualAmount) end
from
    SalesSummary s join Accruals a on
        s.SalesSummaryGuid = a.SalesSummaryGuid
    join AccrualsSetup aa on
        a.AccrualsSetupGuid = aa.AccrualsSetupGuid
    join LookupAccrualTypes la on
        la.AccrualTypeID = aa.AccrualType

where
    convert(varchar(7), InvoiceDate, 20) = @RunDate
    and s.ShortItemNo in (@ShortItemNo1)
group by
    s.ShortItemNo,
    aa.AccrualType

select * from @SalesAccruals

【问题讨论】:

  • 你能给出你想要的临时表中的样本数据吗?
  • 现在 select 语句返回四行,因为有四种不同的应计类型。我希望在临时表中选择包含所有应计类型的一行。我不确定案例陈述是否是解决此问题的最佳方式...
  • 现在它按我想要的方式工作,但列中的其他值是空值。有什么办法可以摆脱这些?

标签: sql sql-server temp


【解决方案1】:

尝试将查询的SELECT 部分更改为...

select
    sum(s.QuantityShipped) QuantityShipped,
    s.ShortItemNo,
    sum(s.ExtendedPrice) ExtendedPrice,
    sum(case when aa.AccrualType=3 then a.AccrualAmount else 0 end),
    sum(case when aa.AccrualType=8 then a.AccrualAmount else 0 end),
    sum(case when aa.AccrualType=2 then a.AccrualAmount else 0 end)

然后从GROUP BY 中删除aa.AccrualType

【讨论】:

  • 工作就像一个魅力。谢谢你,我的朋友。
猜你喜欢
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多