2017-03-09 99 views
0

如果我有:如何在某个WHERE上将列的所有值设置为最大值?

2 baskets of oranges with 7 and 10 each 

3 baskets of peaches with 12 and 15 each 

然后我想设置:

for every orange basket value of maxfruit to 10 and 

for every peach basket value of maxfruit to 15 

我试图

update baskets set maxfruit = (select max(fruitCount) from baskets b where b.fruit = fruit) 

,但它只是所有设置到15 ...

+0

试试这个是否正常:更新篮子设置maxfruit =(从篮子b中选择max(fruitCount)b where b.fruit = fruit)其中basket.fruit ='fruit' – SGventra

+0

整点就是不使用特定名称:( – Zeks

+0

then您必须在插入数据时将maxfruit值设置为最大值。 – SGventra

回答

-1

您更新只是从整个表中拉出最大值,你可以使用子查询来拉出最大值fo R各自水果

UPDATE b 
SET b.maxfruit = b2.fruitCount 
FROM baskets b 
INNER JOIN (SELECT fruit, MAX(fruitCount) AS fruitCount 
      FROM baskets 
      GROUP BY fruit) b2 ON b.fruit = b2.fruit 
+0

我不确定t他的作品在SQLite中。它只是返回一个错误''。 – Zeks

+0

这就是T-SQL你应该可以在SQLlite中做类似的事情 – Moffatt

1

在SQL中,当您正在引用其名称的列,那你最终的表实例是最深奥的,除非你使用一个表前缀。

所以fruit是指最内层的实例b。这意味着b.fruitfruit始终是相同的值。

要引用外部表的实例,您必须使用外部表的名称:

update baskets 
set maxfruit = (select max(fruitCount) 
       from baskets b 
       where b.fruit = baskets.fruit); 
           ^^^^^^^^ 

(而不是b.fruit,你可以写只是fruit,但可能是不清楚的。)

相关问题