Sql 将标题表值分配给另一个表,并分配给具有相同id的多行
我需要有关SQL Server的帮助,了解如何将标题表值分发到另一个表中具有相同id的多行:- 表A:-Sql 将标题表值分配给另一个表,并分配给具有相同id的多行,sql,sql-server,Sql,Sql Server,我需要有关SQL Server的帮助,了解如何将标题表值分发到另一个表中具有相同id的多行:- 表A:- Id | Value ---+-------- 1 | 40 2 | 21 表B:- Id | Qty ---+------- 1 | 20 1 | 13 2 | 1 结果应该是:- Id | Value | Qty -------------------- 1 | 20 | 2
Id | Value
---+--------
1 | 40
2 | 21
表B:-
Id | Qty
---+-------
1 | 20
1 | 13
2 | 1
结果应该是:-
Id | Value | Qty
--------------------
1 | 20 | 20
1 | 20 | 13
2 | 21 | 1
下面的逻辑将把值平均分配给所有行
SELECT *,
(SELECT Value FROM A WHERE A.id = B.id)/COUNT(*) OVER(PARTITION BY id) Value
FROM B
输出为-
Id Qty Value
1 13 20
1 20 20
2 1 21
但是,如果要为所有行分配相同的值,请执行以下操作-
SELECT *,
(SELECT Value FROM A WHERE A.id = B.id) Value
FROM B
或
输出将是-
Id Qty Value
1 20 40
1 13 40
2 1 21
请尝试使用此简单连接
SELECT ta.id,
ta.value / (SELECT ( Count(tmp.id) )
FROM tb AS tmp
WHERE tmp.id = ta.id
GROUP BY tmp.id) AS 'value',
tb.qty
FROM ta
INNER JOIN tb
ON ta.id = tb.id
完整示例(检查图像):
用表替换表变量@Header&@Detail,并删除insert语句。您也可以按照其他一些答案中的建议,通过主查询的子查询来实现这一点,但是对于较大的表,它可能会变慢,因此名为@Counter的表变量首先根据@Detail表变量收集聚合计数
declare @Header table
(
Id int identity(1, 1),
[Value] int
)
declare @Detail table
(
Id int identity(1, 1),
HeaderId int,
Qty int
)
declare @Counter table
(
HeaderId int,
[Count] int
)
insert into @Header values (40)
insert into @Header values (21)
insert into @Detail values (1, 20)
insert into @Detail values (1, 13)
insert into @Detail values (2, 1)
insert into @Counter
select d.HeaderId, count(d.HeaderId)
from @Detail d
group by d.HeaderId
select
h.Id,
h.[Value] / c.[Count] [Value],
d.Qty
from @Header h
join @Detail d
on h.Id = d.HeaderId
join @Counter c
on h.Id = c.HeaderId
只需使用窗口函数除以值:
select tb.id, ta.value / count(*) over (partition by ta.id) as value, tb.qty
from ta join
tb
on ta.id = tb.id;
请注意,由于这些是整数,您可能希望使用以下方法避免整数除法:
select tb.id, ta.value * 1.0 / count(*) over (partition by ta.id) as value, tb.qty
是一个dbfiddle。这看起来像一个简单的连接,而不是任何类型的分发。也没有头球。第一个结果应该是
40
,而不是20
我指的是表a中表b上的值分布,其中a.id=b.idYou没有显示任何类型的分布。简单的select*从A.Id=b.Id上的内部联接b返回您想要的结果查看值我需要与idIf相等的值如果我有1 L记录,上层查询会很慢,因为我们在select语句中使用查询您的实际需求是什么?在每行中分配40个?或者只需将40添加到具有相同id的每一行?对于id,结果值应为201@NiteeshKumar,请检查更新的解决方案以获得所需的输出
declare @Header table
(
Id int identity(1, 1),
[Value] int
)
declare @Detail table
(
Id int identity(1, 1),
HeaderId int,
Qty int
)
declare @Counter table
(
HeaderId int,
[Count] int
)
insert into @Header values (40)
insert into @Header values (21)
insert into @Detail values (1, 20)
insert into @Detail values (1, 13)
insert into @Detail values (2, 1)
insert into @Counter
select d.HeaderId, count(d.HeaderId)
from @Detail d
group by d.HeaderId
select
h.Id,
h.[Value] / c.[Count] [Value],
d.Qty
from @Header h
join @Detail d
on h.Id = d.HeaderId
join @Counter c
on h.Id = c.HeaderId
select tb.id, ta.value / count(*) over (partition by ta.id) as value, tb.qty
from ta join
tb
on ta.id = tb.id;
select tb.id, ta.value * 1.0 / count(*) over (partition by ta.id) as value, tb.qty