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

时间:2015-05-21 09:12:09

标签: sql oracle11g max min

我正在尝试在下面的查询中添加max和min:

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

所需的结果是显示计数中项目最多的类别,并显示计数中项目最少的类别。

CURRENT OUTPUT:

CATEGORY COUNT
Sedan    25
SUV      15
TRUCK    15
AWD      10

期望的输出:

CATEGORY COUNT
Sedan    25
AWD      10

我基本上想要显示在这个例子中将是SEDAN的最大数量以及将是AWD的最小类别数

我认为这需要一个带有嵌套子查询的HAVING语句,任何帮助都会有很大的帮助

我正在使用Oracle 11g

4 个答案:

答案 0 :(得分:2)

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; 

答案 1 :(得分:1)

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

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小提琴:http://www.sqlfiddle.com/#!4/555515/18/0

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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 |