【问题标题】:SQLite - How to count row excluding row having the same values of a specific columnSQLite - 如何计算不包括具有特定列相同值的行的行
【发布时间】:2020-08-27 12:10:17
【问题描述】:

有一个表名为:assembly

列:

id: number
partId: number
index: number

对于一个程序集,我有一个索引为:1、2、3 的零件。

但我可以替换索引 2 处的部分,所以我有 2 个具有相同索引的部分:

id partId   index
1  234      1
1  456      2
1  789      2
1  765      3

我的组件是零件 234、456 或 789、765。

我需要知道我的装配中有多少零件(3 个零件)

我试过了:

select count(assembly.index) from assembly where assembly.id in (1) group by assembly_id

我得到:4

好的,这很正常。

我想通过对索引进行分组,我会得到真正的计数:

我试过了:

select count(assembly.index) from assembly where assembly.id in (1) group by assembly.id and assembly.index

我得到 2 行,计数为 2

我应该得到一个计数为 3 的单行。

另外,如果我更改 where 语句以获取许多 assemble like 的计数

where assembly.id in (1,2,3)

我在每个程序集中得到一排计数错误。

有谁知道我怎样才能得到准确的计数?

谢谢

【问题讨论】:

  • 我不明白。如果您有一个程序集的三个索引,这是否意味着需要 3 个产品?为什么你的例子只给出了两个?

标签: sql sqlite group-by count where-clause


【解决方案1】:

这是你想要的吗?

select count(distinct a.index) no_indexes
from assembly a
where a.id = 1

这给你一行,计数为 3。

如果您希望每个id 有一条记录,那么:

select a.id, count(distinct a.index) no_indexes
from assembly a
group by id 

旁注:index 是所有 sql 方言中的保留字,因此不适合作为列名。

【讨论】:

  • 您的索引是正确的,非常感谢,现在可以使用了!
猜你喜欢
  • 2014-12-08
  • 1970-01-01
  • 2020-10-31
  • 2017-11-04
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多