我是SQL的新手,已经阅读了SQL上的StackOverflow帖子以试图解决这个问题,以及其他来源并且无法在SQL中执行此操作.开始...
我有一个包含3列和数千行的表,其中包含前2列的数据.第三列当前为空,我需要根据第一列和第二列中已有的数据填充第三列.
假设我在第一列中有状态,在第二列中有水果条目.我需要编写一个SQL语句来计算每个水果来自的不同状态的数量,然后将这个流行度数字插入每行的第三列.该行中的流行数为1表示水果仅来自一个州,流行数为4表示水果来自4个州.所以我的表目前是:
state fruit popularity
hawaii apple
hawaii apple
hawaii banana
hawaii kiwi
hawaii kiwi
hawaii mango
florida apple
florida apple
florida apple
florida orange
michigan apple
michigan apple
michigan apricot
michigan orange
michigan pear
michigan pear
michigan pear
texas apple
texas banana
texas banana
texas banana
texas grape
Run Code Online (Sandbox Code Playgroud)
我需要弄清楚如何计算然后更新第三列,名为popular,这是导出该水果的状态数.目标是产生(对不起的双关语)下表,根据上表,"苹果"出现在所有4个州,橙子和香蕉出现在2个州,猕猴桃,芒果,梨和葡萄只出现在1状态,因此他们相应的人气数字.
state fruit popularity
hawaii apple 4
hawaii apple 4
hawaii banana 2
hawaii kiwi 1
hawaii kiwi 1
hawaii mango 1
florida apple 4
florida apple 4
florida apple 4
florida orange 2
michigan apple 4
michigan apple 4
michigan apricot 1
michigan orange 2
michigan pear 1
michigan pear 1
michigan pear 1
texas apple 4
texas banana 2
texas banana 2
texas banana 2
texas grape 1
Run Code Online (Sandbox Code Playgroud)
我的小程序员大脑说试图找出一种在某种脚本中循环数据的方法,但是在SQL和数据库上读一点,看起来你不会在SQL中编写冗长而缓慢的循环脚本.我甚至不确定你能不能?但相反,有更好/更快的方法在SQL中执行此操作.
任何人都知道如何在SQL语句中计算和更新每一行的第三列,这里称为流行度,并且对应于每个水果来自的状态数量?感谢阅读,非常感谢任何帮助.
到目前为止,我已经尝试过以下这些SQL语句,这些语句输出但不能完全满足我的需求:
--outputs those fruits appearing multiple times in the table
SELECT fruit, COUNT(*)
FROM table
GROUP BY fruit
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
--outputs those fruits appearing only once in the table
SELECT fruit, COUNT(*)
FROM table
GROUP BY fruit
HAVING COUNT(*) = 1
--outputs list of unique fruits in the table
SELECT COUNT (DISTINCT(fruit))
FROM table
Run Code Online (Sandbox Code Playgroud)
如果您想简单地更新表的优先级,它将如下所示:
update my_table x
set popularity = ( select count(distinct state)
from my_table
where fruit = x.fruit )
Run Code Online (Sandbox Code Playgroud)
如果您想选择数据,则可以使用分析查询:
select state, fruit
, count(distinct state) over ( partition by fruit ) as popularity
from my_table
Run Code Online (Sandbox Code Playgroud)
这提供了每个水果的不同状态的数量。
| 归档时间: |
|
| 查看次数: |
9081 次 |
| 最近记录: |