删除程序对不同值的SQL计数

删除程序对不同值的SQL计数,sql,r,sqlite,aggregation,Sql,R,Sqlite,Aggregation,我有一个数据集,看起来像: Fruit Quantity apple 1/2 apple 2/2 apple 2/2 orange 1/3 orange 1/1 orange 2/10 grape 4/10` 第一个数字是指每个水果所在的板条箱。这是一个庞大的数据集,我想要一个sql代码,可以聚合每个水果有多少箱 我尝试了许多不同的方法来计数,但无法识别数据集中的第一个数字。我也尝试过许多r软件包,包括ply和data.table

我有一个数据集,看起来像:

   Fruit Quantity 
    apple 1/2
    apple 2/2
    apple 2/2
    orange 1/3
    orange 1/1
    orange 2/10
    grape 4/10`
第一个数字是指每个水果所在的板条箱。这是一个庞大的数据集,我想要一个sql代码,可以聚合每个水果有多少箱

我尝试了许多不同的方法来计数,但无法识别数据集中的第一个数字。我也尝试过许多r软件包,包括ply和data.table来解决这个问题,但运气不佳,使用这些工具或任何其他r软件包的任何想法都将受到欢迎

有什么想法吗

澄清 我期望的输出如下所示

fruit count
apple 2
orange 2
grape 1


使用sqlite寻找答案你可以使用字符串操作来获取字符串的部分,然后对水果进行分组,并告知有多少不同的板条箱编号

对于带有
Shipping
字段的表
ShippingRecords
,该字段应为:

select Fruit, count(distinct Crate)
from (
  select
    Fruit = left(Shipping, charindex(' ', Shipping) - 1),
    Crate = substring(Shipping, charindex(' ', Shipping) + 1, charindex('/', Shipping) - charindex(' ', Shipping) - 1)
  from ShippingRecords
) y
group by Fruit
结果:

apple    2
grape    1
orange   2
SQL Fiddle:


如果
水果
数量
是单独的字段,那么它会变得简单一些:

select Fruit, count(distinct Crate)
from (
  select
    Fruit,
    Crate = left(Quantity, charindex('/', Quantity) - 1)
  from ShippingRecords
) y
group by Fruit
SQL Fiddle:


编辑: 使用SQLite,您可以使用
substr
instr
功能:

select Fruit, count(*)
from (
  select distinct
    Fruit,
    Crate = substr(Quantity, 1, instr(Quantity, '/') - 1)
  from ShippingRecords
) y
group by Fruit

使用right和left将名称和分数分开(如果水果名称中有空格,则使用这种方法)。然后以同样的方式分割分数。假定在名为denormalizedFruits的表中有一个名为fruits的列:

select Fruit
  , left(Crates, charindex('/',Crates) - 1) as ReportedCrate
  , right(Crates, charindex('/',reverse(Crates))-1) as ReportedTotalCrates
  , count(*)over(partition by Fruit) as CratesInDatabse
from (
  select left(fruit,charindex(' ',fruit)-1) as Fruit
    ,right(fruit,charindex(' ',reverse(fruit))-1) as Crates
  from denormalizedFruit
  ) f

请访问下面的。

sql将返回您想要实现的确切结果。 我假设如下:

表名:库存
列:水果,数量

您可能需要更改列名

SQL:
是的,一个是包括你尝试过的许多不同的方法。所以,我有一个快速的答案,但最终的产品取决于期望的结果。您能使用这里的5个样本行编辑您的答案,以显示您希望查询的结果吗?您好,Jaaz。您能否确认您使用了原始数据中的哪些列名称。我理解你在SQLFiddle做了什么。但是,从我的原始数据中,您对列名使用了什么?谢谢我也不确定这是否真的有效。我编辑了输入数据,请看一看。@user3609179您的问题没有定义任何列名。因此,我在表中创建了“水果”来表示您发布的字符串集。如果这是不正确的,请在发布问题时更清楚地说明您的模式,谢谢。嘿,Guffa,您能确认您使用了什么行列名吗?谢谢@user3609179:表名为
ShippingRecords
,列名为
Shipping
。再次感谢!您对在sqlite中工作的类似于charindex的东西有什么想法吗?@user3609179:使用
instr
函数。它的格式是否与instr而不是charindex相同?
SELECT Fruit, COUNT(Crates) AS [Count] FROM 
(
    SELECT DISTINCT Fruit, 
           STUFF(Quantity,                                  -- Main String
                 CHARINDEX( '/',Quantity),                  -- Start
                (LEN(Quantity)-CHARINDEX( '/',Quantity)+1), -- Length
                 ''                                         -- Replace with empty string
                 ) AS Crates  
    FROM [Stock]
) As Wrap
GROUP BY Fruit
ORDER BY [Count] DESC