在select语句中分组,拥有和排序

时间:2017-10-03 08:29:29

标签: sql oracle

我有一个表格ABC,其中有2列,PINFROM_DATE。 我希望PIN分组count > 1,并希望在FROM_DATE列上对结果集进行分区。 我试过了,

SELECT pin, from_date, COUNT(*) AS repetition 
from ABC
GROUP BY pin
HAVING COUNT(*) > 1
ORDER BY from_date;

上述声明给出了'not a GROUP BY expression'错误。 如何将所有Group byhavingorder by放在一个select语句中?

4 个答案:

答案 0 :(得分:2)

如果您只想要每个from_date的最新pin,那么:

SELECT pin,
       MAX( from_date ) AS from_date,
       COUNT(*) AS repetition 
FROM   ABC
GROUP BY pin
HAVING COUNT(*) > 1
ORDER BY from_date;

如果您希望每个from_date的{​​{1}}分别为pin,那么from_date中有两个或更多个SELECT pin, from_date, COUNT(*) AS repetition FROM ABC GROUP BY pin, from_date HAVING COUNT(*) > 1 ORDER BY from_date;

from_date

如果您需要pin个,而SELECT pin, from_date FROM ( SELECT pin, from_date, COUNT(*) OVER( PARTITION BY pin ) AS repetition FROM ABC ) WHERE repetition > 1 ORDER BY from_date; 有两个或更多,那么您可以使用分析函数:

FROM microsoft/aspnet:4.6.2
ARG source
WORKDIR /inetpub/wwwroot
COPY ${source:-obj/Docker/publish} .

答案 1 :(得分:0)

尝试:

SELECT pin, MAX(from_date), COUNT(*) AS repetition 
from ABC
GROUP BY pin
HAVING COUNT(*) > 1
ORDER BY MAX(from_date);

或者

SELECT pin, MIN(from_date), COUNT(*) AS repetition 
from ABC
GROUP BY pin
HAVING COUNT(*) > 1
ORDER BY MIN(from_date);

答案 2 :(得分:0)

您不能使用没有聚合功能的选择列,也不能在group by子句中提及 因此,您可以使用子查询获取所需的值,并通过

连接到不在分组中的值
select distinct ABC.pin, ABC.from_date, t.repetition 
from ABC 
inner join  ( 
SELECT pin, COUNT(*) AS repetition 
from ABC
GROUP BY pin
HAVING COUNT(*) > 1 ) t on t.pin = ABC.pin 
order by ABC.from_date

答案 3 :(得分:0)

您的select子句中有2个未聚合的属性:pin, from_date但只按其中一个(pin)分组,因此from_date'不是GROUP BY表达式'

考虑:

 SELECT pin, from_date, COUNT(*) AS repetition 
 from ABC
 GROUP BY pin, from_date
 HAVING COUNT(*) > 1
 ORDER BY from_date;