2017-03-09 100 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,但可能是不清楚的。)

相關問題