如何检索表中特定ID的列的最频繁值

时间:2019-06-02 15:15:39

标签: sql sqlite

我正在尝试从SQLite 3数据库表中获取每个特定 ID (公司的 ID )的最频繁值。我尝试使用GROUP BYORDER BY以及COUNT()函数。

SELECT company_id, max(car) 
FROM car_orders 
GROUP by company_id
ORDER by max(car)

对于特定的 company_id (9)我期望会出现“ Audi”,但事实并非如此,因为其“ Volkswagen”(这是错误的)

2 个答案:

答案 0 :(得分:1)

在SQLite的最新版本中,您可以使用窗口函数:

SELECT cc.*
FROM (SELECT company_id, car, COUNT(*) as cnt,
             ROW_NUMBER() OVER (PARTITION BY company_id ORDER BY COUNT(*) DESC) as seqnum
      FROM car_orders
      GROUP by company_id, car
     ) cc
WHERE seqnum = 1;

在早期版本中,它稍微复杂一些:

WITH cc as (
      SELECT company_id, car, COUNT(*) as cnt
      FROM car_orders
      GROUP by company_id, car
     )
SELECT cc.*
FROM cc
WHERE cc.cnt = (SELECT MAX(cc2.cnt)
                FROM cc cc2
                WHERE cc2.company_id = cc.company_id
               );

答案 1 :(得分:1)

类似于您的尝试,请考虑将两个总计(每个汽车和公司计算COUNT和每个公司的相同计数器MAX)相加。下面使用的是CTE中发布的SQLite 3.8.3版本中引入的February 2014

WITH cnt AS ( 
   SELECT company_id, car, COUNT(*) AS car_count
   FROM car_orders 
   GROUP by company_id, car
),
 max_cnt AS (
   SELECT cnt.company_id, MAX(cnt.car_count) as max_count
   FROM cnt
   GROUP BY cnt.company_id
)

SELECT cnt.company_id, cnt.car
FROM cnt
INNER JOIN max_cnt
  ON cnt.company_id = max_cnt.company_id
  AND cnt.car_count = max_cnt.max_count