如何在SQL Server中为一项添加两条记录?
我有一张这样的桌子:如何在SQL Server中为一项添加两条记录?,sql,sql-server,Sql,Sql Server,我有一张这样的桌子: Parent date currency_type currency --------------------------------------------- 4106 2016/06/11 EUR 3000.00 2055 2017/06/10 USD 4000000.00 2055 2017/06/10 EUR 4030000.00 如果一
Parent date currency_type currency
---------------------------------------------
4106 2016/06/11 EUR 3000.00
2055 2017/06/10 USD 4000000.00
2055 2017/06/10 EUR 4030000.00
如果一种美元或欧元类型为空,我有两种类型usd和eur,如何自动添加一行代码
4106 2016/06/11 USD 0
谢谢一个选项是使用包含所有父项、日期和货币类型的日历表进行插入:
INSERT INTO yourTable (Parent, date, currency_type, currency)
SELECT p.Parent, d.date, c.currency_type, 0
FROM (SELECT DISTINCT Parent FROM yourTable) AS p
CROSS JOIN (SELECT DISTINCT date FROM yourTable) AS d
CROSS JOIN (SELECT DISTINCT currency_type FROM yourTable) AS c
LEFT JOIN yourTable t
ON t.Parent = p.Parent AND
t.date = d.date AND
t.currency_type = c.currency_type
WHERE
t.Parent IS NULL;
这一系列交叉联接生成父类型、日期和货币类型的所有可能组合。然后,左侧的反联接将清除当前表中缺少的组合。这种方法假设每个可能的父项、日期和货币类型在当前表中至少存在一次。例如,如果您希望填充当前表中完全缺失的日期,则该操作将失败。在这种情况下,我们必须从头开始完全生成新数据。您需要UNION ALL,如果这些行不存在,第二个查询将创建这些行:
select * from tablename
union all
select
t.parent,
t.date,
case t.currency_type
when 'EUR' THEN 'USD'
when 'USD' THEN 'EUR'
end,
0
from tablename t
where not exists (
select 1 from tablename
where parent = t.parent and currency_type <> t.currency_type
)
order by parent desc, currency_type
使用交叉应用和分组方式
create table #t(
Parent int,
[date] date,
currency_type varchar(3),
currency decimal(20,2)
);
insert #t (Parent,[date], currency_type, currency)
values
(4106,'2016/06/11','EUR',3000.00 ),
(2055,'2017/06/10','USD',4000000.00 ),
(2055,'2017/06/10','EUR',4030000.00 )
;
select
Parent,[date], c.curr currency_type, max(case currency_type when c.curr then currency else 0 end) currency
from #t t
cross apply(
select curr
-- add currencies to the list as needed
from (values ('EUR'),('USD')) c(curr)
) c
group by Parent,[date], c.curr;
感谢这段代码,因为我是sql server中的noob。请注意,此解决方案只处理两种(硬编码的)货币类型。这是要求:我有两种类型usd和EUR感谢这段代码有效,但我是sql server中的noob及其pro级别的noob
create table #t(
Parent int,
[date] date,
currency_type varchar(3),
currency decimal(20,2)
);
insert #t (Parent,[date], currency_type, currency)
values
(4106,'2016/06/11','EUR',3000.00 ),
(2055,'2017/06/10','USD',4000000.00 ),
(2055,'2017/06/10','EUR',4030000.00 )
;
select
Parent,[date], c.curr currency_type, max(case currency_type when c.curr then currency else 0 end) currency
from #t t
cross apply(
select curr
-- add currencies to the list as needed
from (values ('EUR'),('USD')) c(curr)
) c
group by Parent,[date], c.curr;