将 max(count) 和 min(count) 添加到查询中

Adding max(count) and min(count) to query

我正在尝试将最大值和最小值添加到以下查询中:

SELECT category, COUNT(distinct VIN) COUNT
FROM stock
group by category
order by category ASC

期望的结果是显示计数中项目最多的类别和计数中项目最少的类别。

当前输出:

CATEGORY COUNT
Sedan    25
SUV      15
TRUCK    15
AWD      10

期望的输出:

CATEGORY COUNT
Sedan    25
AWD      10

我基本上想显示最大数量,在此示例中为 SEDAN,最小类别数量为 AWD

我认为这需要一个带有嵌套子查询的 HAVING 语句,我们将非常感谢您的帮助

我正在使用 Oracle 11g

select 
   count(VIN), 
   Category 
from STOCK
having count(VIN)=
    (
        select max(count(VIN))  
        from STOCK group by project_status_id 
    )
    OR count(project_status_id)=
    (
        select min(count(project_status_id))  
        from project_status group by project_status_id 
     )
group by project_status_id

我能想到的最好的方法是联合两个查询来找到最大和最小计数,如下所示:

Select category, CNT
FROM
(SELECT category, COUNT(distinct VIN) CNT
FROM stock
group by category
Order by CNT asc) a
where RowNum = 1
UNION
Select category, CNT
FROM
(SELECT category, COUNT(distinct VIN) CNT
FROM stock
group by category
Order by CNT desc) a
where RowNum = 1

SQL Fiddle: http://www.sqlfiddle.com/#!4/555515/18/0

select count(VIN), Category 
from STOCK
having count(VIN)=(select max(count(VIN)) from STOCK group by Category )
OR count(VIN)=(select min(count(VIN))  from STOCK group by Category )
group by Category; 

SQL Fiddle

Oracle 11g R2 架构设置:

CREATE TABLE counts ( CATEGORY, "COUNT" ) AS
          SELECT 'Sedan',    25 FROM DUAL
UNION ALL SELECT 'SUV',      15 FROM DUAL
UNION ALL SELECT 'TRUCK',    15 FROM DUAL
UNION ALL SELECT 'AWD',      10 FROM DUAL;

查询 1:

SELECT MAX( CATEGORY ) KEEP ( DENSE_RANK LAST ORDER BY "COUNT" ASC ) AS CATEGORY,
       MAX( "COUNT" ) AS "COUNT"
FROM   COUNTS
UNION ALL
SELECT MIN( CATEGORY ) KEEP ( DENSE_RANK FIRST ORDER BY "COUNT" ASC ) AS CATEGORY,
       MIN( "COUNT" ) AS "COUNT"
FROM   COUNTS

Results:

| CATEGORY | COUNT |
|----------|-------|
|    Sedan |    25 |
|      AWD |    10 |