在 SQL 中嵌套计数
nesting a count in SQL
我正在尝试计算具有特定 sku 的商店(商店 1-10)的不同数量。这是我的代码:
SELECT distinct COUNT(*) as total_store
FROM(
select distinct st.*
from (select st.*
from store_table st
)st
WHERE st.store between 1 and 10
AND st.sku = 10101
GROUP BY st.store
HAVING COUNT(*) >= 1
)a;
我一直收到错误消息:
ORA-00979: not a GROUP BY expression 00979. 00000 - "not a GROUP BY expression"
我不确定它为什么这么说?
您的错误是由于您按 st.store
分组而没有选择数据造成的。您想要在 SELECT 或 GROUP BY 子句中使用的所有非聚合必须出现在两者中。
话虽如此,你把事情搞得太复杂了。如果我们从头开始,您想要商店里的东西:
select * from stores
仅限某些商店
select * from stores where store between 1 and 10
具有特定 SKU
select * from stores where store between 1 and 10 and sku = 10101
现在您想要独特的商店
select distinct store from stores where store between 1 and 10 and sku = 10101
最后您需要独特商店的数量
select count(distinct store)
from stores
where store between 1 and 10
and sku = 10101
您似乎是从集合层而不是逻辑层构建查询。查询是一组条件,如果您需要添加依赖于构造表达式的操作,则只需要创建集合(内联视图等)。在构建查询时,重点关注附加逻辑的分层。如果结果查询与您所说的相比看起来太复杂,那么有可能是这样。
基于 table 名称 STORES 我实际上假设它在 STORE 上是唯一的(并且这是主键因此非空)所以你不需要执行附加排序以使其独一无二
select count(*)
from stores
where store between 1 and 10
and sku = 10101
在 SQL 中,当您使用 group by 时,您必须定义 select 不能使用 * 的字段,并且只能定义一个具有 group by 的字段。
是的,您可以使用 * 那么您必须需要声明分组依据中的所有字段。
另外需要把所有带聚合功能的Field都放上,但是带group by的Fields是不允许使用聚合的。
我正在尝试计算具有特定 sku 的商店(商店 1-10)的不同数量。这是我的代码:
SELECT distinct COUNT(*) as total_store
FROM(
select distinct st.*
from (select st.*
from store_table st
)st
WHERE st.store between 1 and 10
AND st.sku = 10101
GROUP BY st.store
HAVING COUNT(*) >= 1
)a;
我一直收到错误消息:
ORA-00979: not a GROUP BY expression 00979. 00000 - "not a GROUP BY expression"
我不确定它为什么这么说?
您的错误是由于您按 st.store
分组而没有选择数据造成的。您想要在 SELECT 或 GROUP BY 子句中使用的所有非聚合必须出现在两者中。
话虽如此,你把事情搞得太复杂了。如果我们从头开始,您想要商店里的东西:
select * from stores
仅限某些商店
select * from stores where store between 1 and 10
具有特定 SKU
select * from stores where store between 1 and 10 and sku = 10101
现在您想要独特的商店
select distinct store from stores where store between 1 and 10 and sku = 10101
最后您需要独特商店的数量
select count(distinct store)
from stores
where store between 1 and 10
and sku = 10101
您似乎是从集合层而不是逻辑层构建查询。查询是一组条件,如果您需要添加依赖于构造表达式的操作,则只需要创建集合(内联视图等)。在构建查询时,重点关注附加逻辑的分层。如果结果查询与您所说的相比看起来太复杂,那么有可能是这样。
基于 table 名称 STORES 我实际上假设它在 STORE 上是唯一的(并且这是主键因此非空)所以你不需要执行附加排序以使其独一无二
select count(*)
from stores
where store between 1 and 10
and sku = 10101
在 SQL 中,当您使用 group by 时,您必须定义 select 不能使用 * 的字段,并且只能定义一个具有 group by 的字段。 是的,您可以使用 * 那么您必须需要声明分组依据中的所有字段。 另外需要把所有带聚合功能的Field都放上,但是带group by的Fields是不允许使用聚合的。