获得最高计数的组

时间:2018-01-28 15:30:37

标签: sql sql-server

我正在尝试编写一个SQL查询,它将为我提供具有最高价值的组。

我有一个表Crime,其中有两个外键,指向表DistrictCrimeType。我必须选择最受欢迎的'罪行及其地区。

到目前为止,我设法写了这样的东西:

SELECT CrimeType.Category, District.Name, count(*) as NoOfCrimes
FROM Crime
INNER JOIN CrimeType ON Crime.id_crime = CrimeType.id
INNER JOIN District ON Crime.id_district = District.id
GROUP BY CrimeType.Category, District.Name
ORDER BY NoOfCrimes
;

这几乎可行,但我看到每个区域的每一个犯罪和数量,例如:

Rape   | Downtown | 10
Murder | Downtown | 5
Rape   | Queens   | 2
Theft  | Queens   | 7

预期产出:

Rape   | Downtown | 10
Theft  | Queens   | 7

我只需要每个地区最常见的犯罪行为 - 不要重复。

编辑:添加了预期输出。现在我看到每种类型的犯罪及其地区和发生次数,但我需要每个地区最常见的犯罪。

4 个答案:

答案 0 :(得分:0)

你应该可以使用ROW_NUMBER()函数来获得最高的一个,这应该有效:

WITH Crime(Category,
           Name,
           NoOfCrimes,
           num)
     AS (
     SELECT CrimeType.Category,
            District.Name,
            COUNT(*) AS NoOfCrimes,
            ROW_NUMBER() OVER(PARTITION BY Name ORDER BY COUNT(Crime.id_crime))
     FROM Crime
          INNER JOIN CrimeType ON Crime.id_crime = CrimeType.id
          INNER JOIN District ON Crime.id_district = District.id
     GROUP BY CrimeType.Category,
              District.Name
     ORDER BY NoOfCrimes)
     SELECT Category,
            Name,
            NoOfCrimes
     FROM Crime
     WHERE num = 1;

我还没有能够测试它

答案 1 :(得分:0)

由于您已拥有自己的查询,我更愿意使用当前查询(在您的帖子中)并转换为子查询,这将有助于您进一步过滤结果。

示例:

SELECT CrimeType, District, MAX(NoOfCrimes) AS TotalCrimes 
FROM ( 
    SELECT 
    CrimeType.Category  AS CrimeType, 
    District.Name       AS District, 
    count(*)            AS NoOfCrimes
    FROM Crime
    INNER JOIN CrimeType ON Crime.id_crime = CrimeType.id
    INNER JOIN District ON Crime.id_district = District.id
    GROUP BY CrimeType.Category, District.Name
) Crime
GROUP BY CrimeType, District
ORDER BY TotalCrimes DESC

我没有品尝它,但我相信它会有用。

答案 2 :(得分:0)

我设法找到合适的查询。这是:

SELECT Category, Name, NoOfCrimes
FROM (
    SELECT CrimeType.Category, District.Name, count(*) as NoOfCrimes
    FROM Crime
    INNER JOIN CrimeType ON Crime.id_crime_type = CrimeType.id
    INNER JOIN District ON Crime.id_district = District.id
    GROUP BY CrimeType.Category, District.Name
) AS MostCommonCrimes
WHERE NoOfCrimes = (
    SELECT MAX(NoOfCrimes) from MostCommonCrimes a where a.Name = MostCommonCrimes.Name
);

不幸的是,@ dbajtr和@ iSR5答案没有给出正确的结果。

答案 3 :(得分:0)

您可以使用ROW_NUMBER()编写查询:

select Category,
       Name,
       NoOfCrimes
from(   
SELECT row_number() over(partition by District.Name order by count(*) desc) as rownum,
CrimeType.Category, District.Name, count(*) as NoOfCrimes
FROM Crime
INNER JOIN CrimeType ON Crime.id_crime = CrimeType.id
INNER JOIN District ON Crime.id_district = District.id
GROUP BY CrimeType.Category, District.Name
--ORDER BY NoOfCrimes
)as T
where rownum =1
;

SQL Fiddle here..希望这会有所帮助!!