此查询的目标是使用与CountryCode和ProductCode匹配的Table2中的最高和最低价格来更新表1中的MinPrice和MaxPrice列。
当我运行此查询时,表1中的Max和Minprice的整个列将填充来自select查询的第一个值。
如果我自己运行选择查询,则会显示每个产品每个国家/地区的正确最小值和最大值。
UPDATE Table1
SET MinPrice = MinOfPrice, Maxprice = MaxOfPrice
FROM (SELECT Min(lp.Price) AS MinOfPrice, Max(lp.Price) AS MaxOfPrice
FROM Table2 lp INNER JOIN Table1 d ON lp.CountryCode = d.CountryCode AND
lp.ProductCode = d.ProductCode
GROUP BY lp.CountryCode, lp.ProductCode, lp.PriceOriginTypeCode) h ;
答案 0 :(得分:1)
我认为这将是您的解决方案,或者几乎与您的解决方案类似。
UPDATE Table1
SET table1.MinPrice = lp.MinOfPrice, table1.Maxprice = lp.MaxOfPrice
FROM Table1 INNER JOIN ( SELECT top 100 percent CountryCode, ProductCode, MAX(Price) as MaxOfPrice, MIN(Price) as MinOfPrice FROM Table1 group by CountryCode, ProductCode) as lp ON lp.CountryCode = Table1.CountryCode AND
lp.ProductCode = Table1.ProductCode
答案 1 :(得分:1)
只解释我的评论
UPDATE Table1
SET MinPrice = MinOfPrice, Maxprice = MaxOfPrice
FROM (SELECT Min(lp.Price) AS MinOfPrice, Max(lp.Price) AS MaxOfPrice, lp.CountryCode,lp.ProductCode
FROM Table2 lp INNER JOIN Table1 d ON lp.CountryCode = d.CountryCode AND
lp.ProductCode = d.ProductCode
GROUP BY lp.CountryCode, lp.ProductCode, lp.PriceOriginTypeCode) h join Table1 on Table1.ProductCode=h.ProductCode and Table1.CountryCode=h.CountryCode
答案 2 :(得分:1)
我想您当前的查询正在修改table1的每条记录的最小值和最大值,请尝试通过通用列更新以下内容
UPDATE Table1
SET MinPrice = MinOfPrice, Maxprice
= MaxOfPrice
FROM (SELECT Min(lp.Price) AS
MinOfPrice, Max(lp.Price) AS
MaxOfPrice
FROM Table 2 lp INNER JOIN Table1 d
ON lp.CountryCode = d.CountryCode
AND
lp.ProductCode = d.ProductCode
GROUP BY lp.CountryCode,
lp.ProductCode,
lp.PriceOriginTypeCode) h
where h.some_common_column =
Table1.common_column
-- make this query as corelated via above where clause
答案 3 :(得分:0)
您应该在子查询中获取汇总值,然后进行联接。像这样:
update t1
set t1.minPrice = t2.minPrice
,t1.maxPrice = t2.maxPrice
from table1 t1
inner join (
select min(price) minPrice
,max(price) maxPrice
,productCode
,countryCode
from table2
group by productCode
,countryCode
) t2 on t2.productCode = t.productCode
and t2.countryCode = t.countryCode
答案 4 :(得分:0)
尝试一下:
UPDATE Table1
SET MinPrice = h.MinOfPrice
,Maxprice = h.MaxOfPrice
FROM (
SELECT d.CountryCode, d.ProductCode,
Min(lp.Price) AS MinOfPrice,
Max(lp.Price) AS MaxOfPrice
FROM Table 2 lp
INNER JOIN Table1 d
ON lp.CountryCode = d.CountryCode
AND lp.ProductCode = d.ProductCode
GROUP BY d.CountryCode, d.ProductCode
) h ;
我已经摆脱了lp.PriceOriginTypeCode,因为我也不知道这是否也是TABLE1的一部分
答案 5 :(得分:0)
您必须将Table1带出子查询。而且我不明白为什么要按三列分组-这样一来,一个CountryCode-ProductCode组合可以有几行。
UPDATE t
SET MinPrice = h.MinOfPrice, Maxprice = h.MaxOfPrice
FROM Table1 t
JOIN (
SELECT lp.CountryCode,
lp.ProductCode,
Min(lp.Price) AS MinOfPrice,
Max(lp.Price) AS MaxOfPrice
FROM Table2 lp
GROUP BY lp.CountryCode, lp.ProductCode
, lp.PriceOriginTypeCode -- why do you also group by this column?
) h ON h.CountryCode = t.CountryCode AND h.ProductCode = t.ProductCode;