我有一个表格ABC,其中有2列,PIN
和FROM_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 by
,having
和order by
放在一个select
语句中?
答案 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;