我有一个具有以下结构的db表:
CREATE table credite(
nr_contract char(30),
data_incheierii date,
rata_dobinzii int,
valoare_credit float,
nr_rate int,
cod_client char(30),
PRIMARY key (nr_contract),
FOREIGN KEY(cod_client) REFERENCES clienti(cod_client)
);
一些示例数据:
insert into credite
Values ('xsdfghu77','2007-04-02',7.8,20000,12,'43e3rtysr');
insert into credite
Values ('xdfgui767','1980-04-11',7.8,100000,12,'43e3rtyhu');
insert into credite
Values ('xcvbhyty7','1999-10-01',7.8,300000,24,'43e3rtyhv');
insert into credite
Values ('xzasdrtgh','2000-04-02',5.0,10000,6,'43e3rtysr');
insert into credite
Values ('xsdfghu77','2007-04-02',7.8,20000,12,'43e3rtysr');
我需要找到最大贷款数量的日期。 (data_incheierii,大多数时间都包含在样本数据中)
我试过了:
SELECT
MAX(d.incheierii) FROM(Select COUNT(data_incheierii) as incheierii from credite) as d
但我无法返回data_incheierii,因为我遇到语法错误。如何正确编写查询?
答案 0 :(得分:2)
基本上,你可以这样做:
select date_created_loan, count(*) as cnt
from credite
group by date_created_loan
order by count(*) desc
fetch first 1 row only;
注意:fetch first 1 row only
是获取第一行的ANSI标准语法。有些数据库使用limit
;有些人使用select top (1)
;一些人也使用其他结构。
在SQL Server中,您还可以执行以下操作:
select top (1) date_created_loan, count(*) as cnt
from credite
group by date_created_loan
order by count(*) desc;
如果您想要所有最佳日期,可以使用top (1) with ties
。
答案 1 :(得分:1)
你应该尝试这个SQL查询。
SELECT top 1 CAST(MONTH(datecolumn) AS VARCHAR(2)) + '-' + CAST(YEAR(datecolumn) AS VARCHAR(4)) AS MonthYear,
count(*) AS mycount
FROM mytablename
GROUP BY CAST(MONTH(datecolumn) AS VARCHAR(2)) + '-' + CAST(YEAR(datecolumn) AS VARCHAR(4))
ORDER BY mycount desc