连接两个表并按ID和最后日期分组SQL SERVER

时间:2019-04-03 08:09:05

标签: sql sql-server sql-server-2008

我在sql server上有两个表,并已将它们与联接放在一起。这导致t1的标识符加倍。 而且我想按t1.id分组,并在MySql中设法解决它的最后日期,但是在sql-server中我找不到解决方法

结果查询:

{
            "server": true,
            "bootstrap_expect": 3,
            "data_dir": "/tmp/consul",
            "node_name": "agent-one",
            "bind_addr": "ip address 2",
            "enable_script_checks": true,
            "start_join": ["ip of agent 1"]
    }

我想要得到:

+-------+---------+------------+
| t1.id | t1.name |  t2.date   |
+-------+---------+------------+
|     1 | jhon    | 2019-04-03 |
|     1 | jhon    | 2019-04-01 |
|     2 | Beef    | NULL       |
|     3 | Peet    | NULL       |
+-------+---------+------------+

我尝试:

+-------+---------+------------+
| t1.id | t1.name |  t2.date   |
+-------+---------+------------+
|     1 | jhon    | 2019-04-03 |
|     2 | Beef    | NULL       |
|     3 | Peet    | NULL       |
+-------+---------+------------+

Sql服务器不允许我不添加t2.date进行分组:(

请帮助我!

3 个答案:

答案 0 :(得分:1)

除了那些是设置函数参数的列之外,您通常GROUP BYSELECT具有相同的列:

SELECT t1.id, t1.name, max(t2.date) t2date
FROM t1
LEFT JOIN t1 ON t1.id = t2.id
group by  t1.id, t1.name
ORDER BY t2date desc

顺便说一句,不需要子查询。

答案 1 :(得分:0)

尝试以下-

SELECT t1.id, t1.name, max(t2.date)
FROM t1 LEFT JOIN t1 ON t1.id = t2.id
GROUP BY a.id,a.name

答案 2 :(得分:0)

Select * FROM 
(
SELECT DISTINCT ON (t1.id), t1.name, t2.date
FROM t1
LEFT JOIN t1 ON t1.id = t2.id
ORDER BY t2.date desc
) a
GROUP BY a.id,a.name, t2.date

尝试这个。...