SQL中的错误。使用计数时的不同值
这是我的桌子SQL中的错误。使用计数时的不同值,sql,oracle,Sql,Oracle,这是我的桌子 +-----+-----+-----+-------+-------+---------+ | pa | pl | rp | corp | year | rating | |-----+-----+-----+-------+-------+---------| | pa1 | pl1 | rp1 | a1 | 2016 | 6 | | pa1 | pl1 | rp1 | a1 | 2017 | 7 | | pa1 | pl1 |
+-----+-----+-----+-------+-------+---------+
| pa | pl | rp | corp | year | rating |
|-----+-----+-----+-------+-------+---------|
| pa1 | pl1 | rp1 | a1 | 2016 | 6 |
| pa1 | pl1 | rp1 | a1 | 2017 | 7 |
| pa1 | pl1 | rp1 | a2 | 2016 | 6.5 |
| pa1 | pl1 | rp1 | a2 | 2017 | 7.5 |
| pa1 | pl1 | rp2 | a1 | 2016 | 2 |
| pa1 | pl1 | rp2 | a1 | 2017 | 1.5 |
| pa1 | pl1 | rp2 | a2 | 2016 | 4 |
| pa1 | pl1 | rp2 | a2 | 2017 | 4.5 |
+-------------------------------------------+
它的名字是list
我写的查询是为了找到平均值随时间增加的位置
这是我的问题
select count(sq.rp)
from
(select l1.pa, l1.pl, l1.rp, l1.corp, l1.rating as r1, l2.rating as r2
from list l1, list l2
where l1.year = '2016' and l2.year = '2017' and l1.pa = l2.pa
and l1.pl = l2.pl and l1.rp = l2.rp and l1.corp = l2.corp) sq
group by pa, pl, rp
having (avg(sq.r2)-avg(sq.r1)) > 0
当我不在第一行使用计数时(或用此行替换第一行
select sq.rp
它以一行“rp1”显示输出结果
+-----+
| rp |
|-----|
| rp1 |
+-----+
但当我同时使用'count'关键字时,它将计数显示为2。
我不明白原因。没有聚合函数的GROUP BY与使用
DISTINCT
相同,因此只有一行。GROUP BY
与聚合函数结合使用,将聚合函数应用于组的所有行,因此2.在没有该组的情况下执行内部选择,您将请注意,由于联接,它返回两行。没有聚合函数的GROUP BY
与使用DISTINCT
相同,因此只有一行。GROUP BY
与聚合函数结合在一起,将聚合函数应用于组的所有行,因此2.在没有gr的情况下执行内部选择您将看到,由于连接,它返回两行。考虑下面的示例
with x as
(select 'a' idx, 10 from dual union all
select 'a' idx, 20 from dual)
select idx from x group by idx
在第一个示例中,您选择了idx&groupbyidx,但我们没有提供任何聚合函数,但我们仍在按照进行分组
在每个组中,分组列中没有两行具有相同的值
所以它实际上只是对idx列进行了区分
尝试下面的group by和count组合,您可能会理解查询:
with x as
(select 'a' idx, 10 from dual union all
select 'a' idx, 20 from dual)
select idx,count(idx) from x group by idx
考虑下面的例子
with x as
(select 'a' idx, 10 from dual union all
select 'a' idx, 20 from dual)
select idx from x group by idx
在第一个示例中,您选择了idx&groupbyidx,但我们没有提供任何聚合函数,但我们仍在按照进行分组
在每个组中,分组列中没有两行具有相同的值
所以它实际上只是对idx列进行了区分
尝试下面的group by和count组合,您可能会理解查询:
with x as
(select 'a' idx, 10 from dual union all
select 'a' idx, 20 from dual)
select idx,count(idx) from x group by idx
不清楚您需要获得的结果是什么,但对我来说,更可读的是已计算平均值的联接表,然后只需选择您感兴趣的列。请尝试以下示例: 表“列表”应该适合您的示例,将列pa pl和rp替换为k(键)
不清楚您需要获得的结果是什么,但对我来说,更可读的是已计算平均值的联接表,然后只需选择您感兴趣的列。请尝试以下示例: 表“列表”应该适合您的示例,将列pa pl和rp替换为k(键)
@sqluser,请不要截图!请切换到ANSI标准
JOIN
语法,它比逗号分隔的连接更容易阅读。@sqluser,请不要截图!请切换到ANSI标准JOIN
语法,它比逗号分隔的连接更容易阅读。