我试图从一个时间段内得分最多的数据库中返回一个人,
我的数据库表有3个文件,人,日期和点数,
积分将单独添加给人。
我将在数据库中有大约30个人和点表中的无限条目
有人可以帮我处理一个SQL查询,以返回一个具有最大点数的人。
我曾经想过要分两步完成这项工作,1,为所选时期的每个人提供点数总和但不知道如何获得得分最多的人
编辑: 我有以下代码将数据输入数据库
OleDbCommand com = new OleDbCommand("INSERT INTO FlightPoints ([Person], [Flight], [Date_Added], [Points], [Reason]) VALUES (?, ?, ?, ?, ?)", Program.DB_CONNECTION); // add the information into the database
com.Parameters.Add(new OleDbParameter("", cadet[CadetcomboBox.SelectedIndex].ID));
com.Parameters.Add(new OleDbParameter("", cadet[CadetcomboBox.SelectedIndex].Flight.ID));
com.Parameters.Add(new OleDbParameter("", DateTime.Today));
com.Parameters.Add(new OleDbParameter("", PointsnumericUpDown.Value));
com.Parameters.Add(new OleDbParameter("", ReasontextBox.Text));
com.ExecuteNonQuery();
另外两个或两个以上的人实际上可以拥有相同的总分数。我怎么能让所有人得到同样的最高分呢?
答案 0 :(得分:1)
如果我理解正确,你有两个表:
SELECT TOP 1 PersonName FROM
(
SELECT
PersonName,Points
FROM
PersonTable
INNER JOIN (
SELECT
PersonId, SUM(Points) AS Points
FROM
PersonPoint
WHERE
PointDate BETWEEN @StartDate AND @EndDate
GROUP BY PersonId
) AS MaxPoints
ON
MaxPoints.PersonId = PersonTable.PersonId
) q
ORDER BY Points DESC
编辑:考虑到两个或更多人可以拥有相同数量的点数,查询将如下所示,结果如下所示,您可以使用光标选择最高分数:
SELECT PersonName FROM
(
SELECT
PersonName,Points
FROM
PersonTable
INNER JOIN (
SELECT
PersonId, SUM(Points) AS Points
FROM
PersonPoint
WHERE
PointDate BETWEEN @StartDate AND @EndDate
GROUP BY PersonId
) AS MaxPoints
ON
MaxPoints.PersonId = PersonTable.PersonId
) q
ORDER BY Points DESC
答案 1 :(得分:1)
SELECT TOP 1 points_person, Sum(points_value)
FROM dbo.points
GROUP BY points_person
ORDER BY Sum(points_value) DESC
答案 2 :(得分:0)
如果我的布局正确,这适用于SQL Server。
create table #Points
(
[Person] varchar(50) not null,
[Date] DateTime not null,
[Points] int not null
)
insert into #Points (Person,Date,Points) values ('Hans',GETDATE(),1)
insert into #Points (Person,Date,Points) values ('Hans',GETDATE(),2)
insert into #Points (Person,Date,Points) values ('Hans',GETDATE(),3)
insert into #Points (Person,Date,Points) values ('Hans',GETDATE(),4)
insert into #Points (Person,Date,Points) values ('Fritz',GETDATE(),5)
select top 1 Person, Sum(Points)
from #Points
where Date>='2015-02-26 00:00:00' and Date<='2015-02-26 23:59:59'
group by Person
order by 2 desc
drop table #Points