0

我需要一些帮助来构建用于数据库查询的 SQL 命令。数据库有 5 列:

Date(string) 
Name(string) 
number(int)

每个日期、名称和编号可以有多个条目。

我只想为每个日期和名称组合选择一行。问题是这些有多个实例。对于每个日期和名称组合,我想选择具有最高数字的那个。我想按日期订购。例如:

date   |  name  |  number
1/1/1     henry      500
1/1/1     henry      2000 
1/1/1     jacob      5
1/1/1     jacob      8
1/2/1     henry      6

该命令将返回:

1/1/1     henry     2000
1/1/1     jacob     8 
1/2/1     henry     6   

我一直在搞乱一些命令,但我很迷茫。这甚至可能吗?

4

3 回答 3

2

You can use ROW_NUMBER:

WITH cte 
     AS (SELECT date, 
                name, 
                number, 
                rn = Row_number () 
                       OVER( 
                         partition BY date, name 
                         ORDER BY number DESC) 
         FROM   dbo.tablename) 
SELECT date, 
       name, 
       number 
FROM CTE
WHERE  rn = 1 
ORDER  BY date ASC

DEMO

ROW_NUMBER will always select one record per group. If you want to get all rows with the highest number for a given name(if there are more than one) use DENSE_RANK instead.

于 2013-03-18T22:05:50.590 回答
0

尝试按日期和名称分组,然后选择最大数量。像这样(确切的语法可能因您的 sql 版本而异):

select
   date,
   name,
   max(number)
from
   yourtable
group by
   date,
   name
order by
   date asc
于 2013-03-18T22:09:34.280 回答
0
SELECT date, name, MAX(number)
FROM Table1
GROUP BY date, name
ORDER date, name
于 2013-03-18T22:10:56.233 回答