从按SQL限制分组的表中查找重复次数最多的元素

时间:2019-03-20 04:45:21

标签: sql-server

在我的代码中,我有桌子:

CREATE TABLE SERVICE
(
    SER_ID      INT primary key NOT NULL,
    SER_TYPE    VARCHAR(35)     NOT NULL,
    SER_STARTDATE DATE          NOT NULL,
    SER_ENDDATE   DATE,
    LAW_SOCNUM    VARCHAR(8),
    FOL_ID  INT,
    CLI_ID      INT,
    FOREIGN KEY (LAW_SOCNUM) REFERENCES LAWYER ON DELETE SET NULL,
    FOREIGN KEY (FOL_ID) REFERENCES FEILD_OF_LAW ON DELETE SET NULL,
    FOREIGN KEY (CLI_ID) REFERENCES CLIENT ON DELETE SET NULL,

);

和表格:

CREATE TABLE FEILD_OF_LAW
(
    FOL_ID INT PRIMARY KEY NOT NULL,
    FOL_NAME VARCHAR(35) NOT NULL
);

我的任务是找到服务中最常见的名称 给定年份,这只是法律名称的字段。我在获取正确的值时遇到麻烦,因为在FEILD_OF_LAW.FOL_NAME上调用max只会使我的字母顺序最低。这是我尝试过的:

select distinct year(SER_STARTDATE) as 'YEAR', max(fol) as 'MOST_COMMON_SERV'
from SERVICE join (select SERVICE.SER_ID, FEILD_OF_LAW.FOL_NAME as 'fol'
    from SERVICE join FEILD_OF_LAW on SERVICE.FOL_ID = FEILD_OF_LAW.FOL_ID) a1 on SERVICE.SER_ID = a1.SER_ID 
group by year(SER_STARTDATE)

任何人都可以帮我解释一下如何使SERVICE表中出现的FOL_ID重复次数最多,以及如何将其分组为年份。谢谢。

3 个答案:

答案 0 :(得分:0)

我认为您必须使用count聚合函数而不是max wit group by fol_id和top 1一起返回,它会返回大多数重复的year的Fol_id。如果您不想检查所有值,请从查询中删除top 1子句。

        select top 1 year(SER_STARTDATE) as 'YEAR', count(fol) as 
       'MOST_COMMON_SERV',fol
        from SERVICE join (select SERVICE.SER_ID, FEILD_OF_LAW.FOL_NAME as 'fol'
         from SERVICE join FEILD_OF_LAW on SERVICE.FOL_ID = FEILD_OF_LAW.FOL_ID) a1 
        on SERVICE.SER_ID = a1.SER_ID 
        group by year(SER_STARTDATE),fol
        order by count(fol) desc

答案 1 :(得分:0)

这是第一个小组问题。也许试试这个:

with cte (the_year, the_count, the_fol_id, the_fol_name, row_num) AS (
    select datepart(year,ser_startDate), count(*), s.fol_id, fol_name,
        row_number() OVER(PARTITION BY datepart(year,ser_startDate) 
            ORDER BY count(*) DESC) AS rowNum
    from service s
        join feild_of_law f on f.fol_ID=s.fol_id
    group by datepart(year,ser_startDate), s.fol_id, fol_name
)
select *
    from cte 
where cte.row_num=1

cte按每年的出现次数进行分组,并为每个组应用行号,第二部分为每个组选择第一行。

答案 2 :(得分:0)

我读了另一个答案,但是它们有一个问题:只有当您临近一年时,结果才是正确的。 如果您需要一年以上的统计信息,可以这样做:

create view VW_ServiceStats as ( 

Select year(ser_startdate) as year, 
             fol.fol_name, 
            COUNT(*) as [Service Count]
from service ser 
inner join feild_of_law fol 
on ser.fol_id = fol.fol_id
group by  YEAR(ser.ser_startdate),fol.fol_name


)


Select YEAR , max(fol_name), MAX([service count])
from vw_servicestats
group by year

我创建了一个包含第一个分组的视图(year-fol-count)。 然后我每年只选择更多的服务。

我认为这种方式也比其他方式更整洁。