SQL选择 - 插入另一个表中的值(如果不存在)则按另一个值进行分组

时间:2014-08-18 08:47:28

标签: sql-server

我有两张桌子

@sales  --- where I register the daily number of sales
@o_date --- where I register the opening dates

我需要在@o_dates中为每个可用日期填写@sales表中的日期空白,这必须是@sales表中可用的每个代码

请帮助这个选择。

DECLARE @sales TABLE
(
code VARCHAR(10) NOT NULL,
date1 DATETIME NOT NULL,
value NUMERIC(10, 2) NOT NULL
);

INSERT  @sales
(
Code,
Date1,
value
)
VALUES  ('q', '20140708', 51),
('q', '20140709', 3),
('q', '20140710', 5),
('q', '20140711', 6),
('q', '20140712', 2),
('q', '20140713', 7),
('q', '20140714', 24),
('q', '20140715', 24),
('x', '20140709', 25),
('x', '20140710', 16),
('x', '20140711', 66),
('x', '20140712', 23),
('x', '20140713', 35),
('x', '20140714', 57),
('c', '20140712', 97),
('c', '20140714', 71);

DECLARE @o_dates TABLE 
(date2 DATETIME NOT NULL);

INSERT  @o_dates
(date2)
VALUES  ('20140608'),
('20140707'),
('20140708'),
('20140709'),
('20140710'),
('20140711'),
('20140712'),
('20140713'),
('20140714'),
('20140715'),
('20140716'),
('20140717'),
('20140718'),
('20140719'),
('20140720');

1 个答案:

答案 0 :(得分:0)

此查询为您提供每个代码的组合销售和日期,其中销售中缺少日期的值为null:

select code, date1, value from @sales 
union (
    select distinct code, date2, null as value from @sales, @o_dates
    except
    select code, date1, null as value from @sales
    group by code, date1
) 
order by code, date1, value

此查询插入sales表中缺少的日期,其中0为值:

insert @sales 
select distinct code, date2, 0 as value from @sales, @o_dates
except
select code, date1, 0 as value from @sales
group by code, date1

我确信使用连接可以简化这两个查询,但这是我想到的第一个解决方案。

编辑:

上面的选择查询的连接版本应该很容易修改为插入:

select distinct s.code, date2, s2.value from @sales s
cross join  @o_dates d
left join @sales s2
on s.code=s2.code and s2.date1=d.date2
order by code, date2