如何通过条件向结果集添加其他行

时间:2010-04-07 08:17:34

标签: tsql sql-server-2008

我有一张这样的表:

ObjId Date Value
100 '20100401' 12
200 '20100501' 45
200 '20100401' 37
300 '20100501' 75
300 '20100401' 69
400 '20100401' 87

我必须为objId的结果集添加额外的行,其中'20100501'没有数据

**100 '20100501' null**
100 '20100401' 12
200 '20100501' 45
200 '20100401' 37
300 '20100501' 75
300 '20100401' 69
**400 '20100501' null**
400 '20100401' 87

最好的方法是什么?

这是初始表的T-SQL脚本:

declare @datesTable table (objId int, date smalldatetime, value int)
insert @datesTable
select 100, '20100401', 12
union all
select 200, '20100501', 45
union all
select 200, '20100401', 37
union all
select 300, '20100501', 75
union all
select 300, '20100401', 69
union all
select 400, '20100401', 87

select * from @datesTable

2 个答案:

答案 0 :(得分:1)

好的,我现在明白了:-)你想找到没有日期为2010-05-01的条目的objId值,然后用那些objId和那个日期以及一个NULL值插入额外的行 - 使用CTE(通用表格表达式):

;WITH MissingObj AS
(
    SELECT objId 
    FROM @datesTable  d1
    WHERE NOT EXISTS (SELECT objId FROM @datesTable d2 WHERE d2.objId = d1.objId AND d2.date = '20100501')
)
INSERT INTO @datesTable(objId, date, value)
    SELECT
        mo.objId, '20100501', NULL
    FROM    
        MissingObj mo

MissingObj CTE获取“2010-05-01”没有条目的所有objId值,然后使用该objId列表,以下INSERT语句将这些值插入@datesTable 1}}表。

作为旁注:我发现这种方法更容易填写样本表:

declare @datesTable table (objId int, date smalldatetime, value int)

insert into @datesTable(objId, date, value)
   VALUES(100, '20100401', 12),
     (200, '20100501', 45),
     (200, '20100401', 37),
     (300, '20100501', 75)  -- and so forth

SQL Server 2008允许您在(....)中传递多个元组值 - 比union all构造更容易和更易读...

答案 1 :(得分:0)

这可以是一个解决方案:

declare @datesTable table (objId int, date smalldatetime, value int)
insert @datesTable
select 100, '20100401', 12
union all
select 200, '20100501', 45
union all
select 200, '20100401', 37
union all
select 300, '20100501', 75
union all
select 300, '20100401', 69
union all
select 400, '20100401', 87


with objids as (
    select distinct objid
    from @datesTable )
insert into @datesTable(objId, date, value)
select D.objId, '20100501', NULL
from objids D 
where not exists(select * 
    from @datestable T
    where T.objId = D.objId
    and date = '20100501')

select *from @datesTable    
相关问题