1

我的 sql 查询是

select I.[Old Product Code], 
    I.[Trade Name], 
    I.[Short Name], 
    SIL.[BOM Item No_] ,
    CASE when SIL.[Dimension Group Code] = 'IOL' 
        then I.[Group Description] 
        else I.[Short Name] END as GD,
    CASE when SIL.[BOM Item No_] <> '' 
        then 'Kit' end
from [Sales Invoice Header] SIH, [Sales Invoice Line]  SIL, [Item] I 
where I.No_ =  SIL.No_ 
    and SIL.[Document No_] = 'PEXP1213-153' 
    and SIH.No_ = SIL.[Document No_] 
group by I.[Old Product Code], I.[Trade Name], I.[Short Name],  
    SIL.[Dimension Group Code], I.[Group Description], SIL.[BOM Item No_]

我的结果是

电流输出

在这 21 行中,我有 17 行作为套件。我需要将此套件分组并在旧产品代码中显示为一行而不是 17 行的套件。

4

1 回答 1

0

查看您要执行的操作,您可能可以使用类似这样的方法来返回数据:

;with data as
(
  select I.[Old Product Code], 
      I.[Trade Name], 
      I.[Short Name], 
      SIL.[BOM Item No_] ,
      CASE when SIL.[Dimension Group Code] = 'IOL' 
          then I.[Group Description] 
          else I.[Short Name] END as GD,
      CASE when SIL.[BOM Item No_] <> '' 
          then 'Kit' end CombinedKit
  from SalesInvoiceHeader SIH
  inner join SalesInvoiceLine  SIL
    on SIH.No_ = SIL.[Document No_] 
  inner join Item I 
    on I.No_ =  SIL.No_ 
  where SIL.[Document No_] = 'PEXP1213-153' 
),
d2 as
(
  select [Old Product Code],
    [Trade Name],
    [Short Name],
    [BOM Item No_],
    GD,
    CombinedKit,
    row_number() 
      over(partition by CombinedKit order by [Old Product Code]) rn
  from data
) 
select 
    case when combinedkit = 'kit' 
        then 'Kit' else [Old Product Code] end  [Old Product Code],
    [Trade Name],
    [Short Name],
    [BOM Item No_],
    GD
    --, CombinedKit
from d2
where (CombinedKit = 'Kit' and rn = 1)
  or (CombinedKit is null) 

请参阅带有演示的 SQL Fiddle

编辑,如果您想以特定方式订购它,您可以使用Order By语句CASE

;with data as
(
  select I.[Old Product Code], 
      I.[Trade Name], 
      I.[Short Name], 
      SIL.[BOM Item No_] ,
      CASE when SIL.[Dimension Group Code] = 'IOL' 
          then I.[Group Description] 
          else I.[Short Name] END as GD,
      CASE when SIL.[BOM Item No_] <> '' 
          then 'Kit' end CombinedKit
  from SalesInvoiceHeader SIH
  inner join SalesInvoiceLine  SIL
    on SIH.No_ = SIL.[Document No_] 
  inner join Item I 
    on I.No_ =  SIL.No_ 
  where SIL.[Document No_] = 'PEXP1213-153' 
),
d2 as
(
  select [Old Product Code],
    [Trade Name],
    [Short Name],
    [BOM Item No_],
    GD,
    CombinedKit,
    row_number() 
      over(partition by CombinedKit order by [Old Product Code]) rn
  from data
) 
select 
    case when combinedkit = 'kit' 
        then 'Kit' else [Old Product Code] end  [Old Product Code],
    [Trade Name],
    [Short Name],
    [BOM Item No_],
    GD
    --, CombinedKit
from d2
where (CombinedKit = 'Kit' and rn = 1)
  or (CombinedKit is null) 
order by 
  case when combinedkit = 'kit' then 0 else 1 end, [Old Product Code]

请参阅带有演示的 SQL Fiddle

于 2012-12-20T12:46:18.597 回答