关键字之间的组SQL

时间:2012-08-15 11:32:54

标签: sql sql-server-2008 tsql sql-server-2008-r2

问题

我导入的电子表格包含与子元素在同一列上的父组数据。我想为组添加提取列,如下所示。

创建表格

DECLARE @Fruit TABLE
    (
      ProductID INT IDENTITY(1, 1)
                    PRIMARY KEY ,
      FruitName NVARCHAR(20) ,
      FruitCost MONEY
    )

INSERT  INTO @fruit
        ( FruitName, FruitCost )
VALUES  ( 'Berry', NULL )
INSERT  INTO @fruit
        ( FruitName, FruitCost )
VALUES  ( 'BlueBerry', 2 )
INSERT  INTO @fruit
        ( FruitName, FruitCost )
VALUES  ( 'StrawBerry', 2 )
INSERT  INTO @fruit
        ( FruitName, FruitCost )
VALUES  ( 'Citrus', NULL )
INSERT  INTO @fruit
        ( FruitName, FruitCost )
VALUES  ( 'Lemon', 2 )
INSERT  INTO @fruit
        ( FruitName, FruitCost )
VALUES  ( 'Orange', 2 )

SELECT  *
FROM    @Fruit

表格结果

ProductID   FruitName            FruitCost
----------- -------------------- ---------------------
1           Berry                NULL
2           BlueBerry            2.00
3           StrawBerry           2.00
4           Citrus               NULL
5           Lemon                2.00
6           Orange               2.00

必填结果

FruitName            FruitCost             FruitGroup
-------------------- --------------------- --------------------
BlueBerry            2.00                  Berry
StrawBerry           2.00                  Berry
Lemon                2.00                  Citrus
Orange               2.00                  Citrus

2 个答案:

答案 0 :(得分:2)

试试这个

select
    f3.FruitName, f3.FruitCost, f.FruitName
from
    @Fruit f
        inner join
    (
        SELECT  *,
        (Select max(productid) from @Fruit f2 where FruitCost is null and ProductID<=f.ProductID) as fgroup
        FROM    @Fruit f
    ) f3
        on f.ProductID = f3.fgroup
where f3.FruitCost is not null  

答案 1 :(得分:1)

select t.FruitName,t.FruitCost,  
(select FruitName from @fruit t2
  where t2.ProductId in 
  (
    select max(t3.ProductId) from 
    @fruit t3 
    where (t3.FruitCost is null) and (t3.ProductId<t.ProductId)
   )

) FruitGroup
from @Fruit t where (t.FruitCost is not null)