SQL select query did not work

时间:2016-07-11 19:25:36

标签: sql sql-server database greatest-n-per-group

I have a table like below,

Agent   Group   Skill   Peripheral  Route   DateTime    Variable4
55496   NULL    318735  5135    NULL    7/10/2016 10:40 0000000000???NA ALL?15176600??28324000??
55496   53944   124769  5079    36567   7/10/2016 10:41 0000000000???NA ALL?15176600??28324000??
NULL    NULL    124769  5079    36567   7/10/2016 10:41 0000000000???NA ALL?15176600??28324000??

NULL    NULL    296404  5119    NULL    7/10/2016 10:44 0000000000???NA ALL?15176600??28777000??
55497   53944   124769  5079    36567   7/10/2016 10:45 0000000000???NA ALL?15176600??28777000??
NULL    NULL    124769  5079    36567   7/10/2016 10:45 0000000000???NA ALL?15176600??28777000??

55498   NULL    318735  5135    NULL    7/10/2016 10:46 0000000000???NA ALL?15176600??28928000??
55498   53944   124769  5079    36567   7/10/2016 10:46 0000000000???NA ALL?15176600??28928000??
NULL    NULL    124769  5079    36567   7/10/2016 10:46 0000000000???NA ALL?15176600??28928000??

Here you see the Variable4 is same for the each three records, I need one record for each of Variable4, that should be the latest DateTime among those and the Agent field should not be null

Below is what i want,

55496   53944   124769  5079    36567   7/10/2016 10:41 0000000000???NA ALL?15176600??28324000??
55497   53944   124769  5079    36567   7/10/2016 10:45 0000000000???NA ALL?15176600??28777000??
55498   53944   124769  5079    36567   7/10/2016 10:46 0000000000???NA ALL?15176600??28928000??

Can anyone help me to write an SQL query to achieve this?

2 个答案:

答案 0 :(得分:0)

Please be more specific, but I believe a general select query would work.

SELECT Agent, Group, Skill, Peripheral, Route, DateTime, Variable4
FROM table_name
WHERE Variable4 NOT NULL
GROUP BY Variable4 ASC;

答案 1 :(得分:0)

Try like this

SELECT MAX(Agent) Agent, MAX(Group) Group, MAX(Skill) Skill, MAX(Peripheral) Peripheral, MAX(Route) Route, MAX(DateTime) DateTime, Variable4
FROM table_name
GROUP BY Variable4