如何将一行值移动到另一行并删除所有空SQL Server 2008的行

时间:2014-06-09 10:25:20

标签: sql sql-server null

我有一张表格如下

PK   DBName API50 CounterValue
1    NULL    NULL   NULL
2    NULL    NULL   1
3    NULL    NULL   NULL
4    NULL    NULL   NULL
5    NULL    NULL   NULL
6    test1   34.5   NULL
7    NULL    NULL   NULL
8    NULL    NULL   NULL
9    NULL    NULL   NULL
10   NULL    NULL   2
11   test1   38.5   NULL

我希望结果表如下

   DBName API50 CounterValue
    test1  34.5   1
    test1  38.5   2

如下面的问题所述 move one row value to another sql

我正在进行自我加入,但这导致CounterValue没有被填充。希望你们能帮助我。提前谢谢。

4 个答案:

答案 0 :(得分:2)

如果对价值总是与PK一致,

select
    DBName, 
    API50, 
    (select max(CounterValue) from yourtable t1 where t1.pk <= yourtable.pk)
from yourtable
where DBName is not null

答案 1 :(得分:0)

尝试此查询:

SELECT DBName,API50,
       (SELECT TOP 1
           CounterValue
           FROM t
           WHERE CounterValue is not null
           AND PK<=t1.PK
           ORDER BY PK DESC

        ) as CounterValue
FROM t as t1
WHERE DBNAme IS NOT NULL

SQLFiddle demo

答案 2 :(得分:0)

也可以尝试此查询

**选择t.DBName,MAX(t.API50)为API50,tt.CounterValue来自( 选择* from JustTest作为t,其中DBName不为null)为t ,(从JustTest中选择*作为Tt,其中CounterValue不为null)tt 按t.DBName,tt.CounterValue

分组

答案 3 :(得分:0)

尝试此查询

select * from @table1
SELECT t1.ID, t1.DBName, t1.API50, t2.CounterValue
FROM @table1 t1 
INNER JOIN @table1 t2 ON t1.ID > t2.ID
WHERE t1.DBName IS NOT NULL
 AND t2.ID IN (select ID from @table1 where dbname is null and ID < t1.ID)
 AND t2.ID > (select ISNULL(MAX(ID),0) from @table1 where dbname is not null and ID < t1.ID)

选中此SQL FIDDLE