Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用子查询更新表_Sql_Sql Server - Fatal编程技术网

Sql 使用子查询更新表

Sql 使用子查询更新表,sql,sql-server,Sql,Sql Server,我有一个具有以下属性的Foo表: FooID (PK) | Bar | Price 假设样本记录集为: 1 | 332 | 10 2 | 332 | 10 3 | 333 | 5 4 | 334 | 30 4 | 334 | 30 4 | 334 | 30 我希望查询的输出是 1 | 332 | 5 2 | 332 | 5 3 | 333 | 5 4 | 334 | 10 4 | 334 | 10 4 | 334 | 10 换句话说,Price列应该是:Price/N的结果,其中N是给定条

我有一个具有以下属性的Foo表:

FooID (PK) | Bar | Price
假设样本记录集为:

1 | 332 | 10
2 | 332 | 10
3 | 333 | 5
4 | 334 | 30
4 | 334 | 30
4 | 334 | 30
我希望查询的输出是

1 | 332 | 5
2 | 332 | 5
3 | 333 | 5
4 | 334 | 10
4 | 334 | 10
4 | 334 | 10
换句话说,Price列应该是:Price/N的结果,其中N是给定条在记录集中存在的次数

我已通过以下方法计算出存在的钢筋数量:

  select Bar, count(*) as BarCount from Foo GROUP BY Bar
然而,我不知道如何将其应用于价格划分


谢谢

您可以使用窗口函数和分区:

select fooid, bar, 
       price / count(*) over (partition by bar) as new_price
from t;
请注意,SQLServer执行整数除法。因此,如果price是整数,则可以通过以下方法获得更准确的结果:

select fooid, bar, 
       price * 1.0 / count(*) over (partition by bar) as new_price
from t;
编辑:

标题是更新,但问题只提到获得结果。如果要更新,请使用可更新的CTE或子查询:

with toupdate as (
      select t.*, 
             price / count(*) over (partition by bar) as new_price
      from t
     )
update toupdate
    set new_price = price
    where price <> new_price;

使用相关子查询计算除法器:


dbfiddle

您可以使用CTE查找每个条形组的计数,然后加入该CTE以查找商:

WITH cte AS (
    SELECT Bar, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY Bar
)

SELECT t1.FooID, t1.Bar,
   1.0 * t1.Price / t2.cnt AS NewPrice
FROM yourTable t1
INNER JOIN cte t2
    ON t1.Bar = t2.Bar
ORDER BY
    t1.Bar, t1.FooID;

Gordon的答案可能是最快的,因为它可以在一次遍历整个表的过程中找到计数并计算商。我给出的答案需要额外的子查询和联接。

我个人不会在数据库中存储这样的值。主要原因是,否则每次插入、删除或更新行时,都需要使用该ID栏更新每一行。这很可能需要触发器。使用视图可能会更好。当给定的酒吧有不同的价格时会发生什么?你在数学中使用的价格是多少?您是否假设给定酒吧的所有价格都相同?这是一个安全的假设吗?这可能是+1的最佳答案,我自己也会给出,期望Gordon实际上是一个由堆栈溢出创建的AI程序。嘿,StackOverflow。如果你想创建这样一个人工智能程序,我很乐意提供帮助。同意@TimBiegeleisen!谢谢!!这个解决方案是完美的!编辑也是相关的,因为正如你提到的,我忘了在问题上添加更新部分,对此表示抱歉!非常有趣的讨论!就我个人而言,我真的认为Gordon是一个人工智能,尤其是上个月我开始关注sql标签时。。。谢谢你教我们,戈登! fooid | bar | (No column name) ----: | --: | ---------------: 1 | 332 | 5 2 | 332 | 5 3 | 333 | 5 4 | 334 | 10 4 | 334 | 10 4 | 334 | 10
WITH cte AS (
    SELECT Bar, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY Bar
)

SELECT t1.FooID, t1.Bar,
   1.0 * t1.Price / t2.cnt AS NewPrice
FROM yourTable t1
INNER JOIN cte t2
    ON t1.Bar = t2.Bar
ORDER BY
    t1.Bar, t1.FooID;