选择与MAX列值对应的列值

时间:2016-06-24 09:15:32

标签: sql sql-server tsql

我有一个表人,日期为yyyymmDD格式,时间为hhmmssSSS格式

ID    NAME      CREATEDDATE     CREATEDTIME
1      A          20170205       135744300
2      B          20160205       113514368
3      C          20090205       163054942
4      A          20150205       135744301

现在我想在一个查询中计算每个人和最大创建日期以及CORRESPONDING创建的时间

我试过

SELECT NAME, COUNT (ID) AS COUNT, MAX(CREATEDDATE), MAX(CREATEDTIME)
FROM Person

但是这给了我每列的最大日期和最长时间,它没有给我CREATEDTIME对应MAX(CREATEDDATE)

e.g。

查询结果是

NAME   COUNT    MAXCREATEDDATE       CORRESPONDINGCREATEDTIME

A        2        20170205             135744301

CORRESPONDINGCREATEDTIME应为135744300

请帮我做吧

6 个答案:

答案 0 :(得分:2)

您只需使用子查询即可找到每个名称的最大日期并执行内部联接。

测试数据

public int applyNutrientCoefficient() {
    int deathCount = 0;
    Iterator it = guppiesInPool.iterator();
    while (it.hasNext()) {
        Guppy guppyOne = it.next();
        if (randomNumberGenerator.nextDouble() > nutrientCoefficient) {
            if (guppyOne.getIsAlive()) {
                guppyOne.setIsAlive(false);
                deathCount++; // should be inside the if-block i suppose?
            }
        }
    }

    return deathCount;
}

查询

CREATE TABLE #Person (ID int, Name varchar(1), CreatedDate int, CreatedTime int)
INSERT INTO #Person (ID, Name, CreatedDate, CreatedTime)
VALUES
 (1,'A',20170205,135744300)
,(2,'B',20160205,113514368)
,(3,'C',20090205,163054942)
,(4,'A',20150205,135744301)

结果

SELECT
a.Name
,b.CtName CountName
,a.CreatedDate
,a.CreatedTime
FROM #Person a
JOIN    (
            SELECT 
            Name
            ,COUNT(Name) CtName
            ,MAX(CreatedDate) MaxDate 
            FROM #Person 
            GROUP BY Name
        ) b
ON a.Name = b.Name
AND a.CreatedDate = b.MaxDate

答案 1 :(得分:1)

试试这个答案,

SELECT NAME, COUNT(ID) AS COUNT, max(CREATEDDATE), max(CREATEDTIME)
FROM Person
where CREATEDDATE = (select MAX(CREATEDDATE) from Person)
group by NAME

答案 2 :(得分:1)

试试这个

    SELECT DISTINCT
       R.NAME,
       COUNT(1) OVER (PARTITION BY NAME),
       MAX(R.CREATEDDATE) OVER (PARTITION BY NAME ) ,
       MAX(P.CREATEDTIME) OVER (PARTITION BY NAME )
    FROM
        Person

答案 3 :(得分:1)

还有一个,没有连接或子查询

SELECT NAME, COUNT (ID) AS COUNT
  , MaxCREATEDDATE = MAX(cast(CREATEDDATE as bigint)*1000000000 + CREATEDTIME) /1000000000
  , CorrespTime = MAX(cast(CREATEDDATE as bigint)*1000000000 + CREATEDTIME) %1000000000
FROM Person
GROUP by NAME

答案 4 :(得分:0)

您可以在内部查询中计算countmax(CREATEDDATE),然后根据每个人的最长日期加入您的表格以获取时间:

select
   R.NAME,
   R.COUNT,
   R.CREATEDDATE,
   P.CREATEDTIME
from
  (
    SELECT NAME, COUNT (ID) AS COUNT, MAX(CREATEDDATE) as CREATEDDATE
    FROM Person
    group by NAME
  ) as R
  left outer join Person as P on P.NAME = R.NAME and P.CREATEDDATE = R.CREATEDDATE

答案 5 :(得分:0)

data.key['index']