我有两张桌子,比如A和B.
表:A
ID_Sender | Date
________________________
1 | 11-13-2013
1 | 11-12-2013
2 | 11-12-2013
2 | 11-11-2013
3 | 11-13-2013
4 | 11-11-2013
表:B
ID | Tags
_______________________
1 | Company A
2 | Company A
3 | Company C
4 | Company D
结果表:
Tags | Date
____________________________
Company A | 11-13-2013
Company C | 11-13-2013
Company D | 11-11-2013
我已经尝试了GROUP BY with MAX(DATE),但没有运气就失败了,我做了一些内连接和子查询,但未能产生输出。
这是我到目前为止的代码,以及附加输出的图像。
SELECT E.Tags, D.[Date] FROM
(SELECT A.ID_Sender AS Sendah, MAX(A.[Date]) AS Datee
FROM tblA A
LEFT JOIN tblB B ON A.ID_Sender = B.ID
GROUP BY A.ID_Sender) C
INNER JOIN tblA D ON D.ID_Sender = C.Sendah AND D.[Date] = C.Datee
INNER JOIN tblB E ON E.ID = D.ID_Sender
有什么建议吗?我已经拉出了我的头发! (也许你们可以给我一些有用的sql概念,答案不是必要的因为我真的很想自己解决它:))
谢谢!
答案 0 :(得分:5)
SELECT Tags, MAX(Date) AS [Date]
FROM dbo.B INNER JOIN dbo.A
ON B.ID = A.ID_Sender
GROUP BY B.Tags
结果
Company A November, 13 2013 00:00:00+0000
Company C November, 13 2013 00:00:00+0000
Company D November, 11 2013 00:00:00+0000
答案 1 :(得分:0)
试试这个,如果我错了,请让我纠正。在表B中,Id = 2是公司B,我假设..如果它是正确的,那么请继续使用此代码。
declare @table1 table(ID_Sender int, Dates varchar(20))
insert into @table1 values
( 1 , '11-13-2013'),
(1 , '11-12-2013'),
(2 ,'11-12-2013'),
(2 ,'11-11-2013'),
(3 ,'11-13-2013'),
(4 ,'11-11-2013')
declare @table2 table ( id int, tags varchar(20))
insert into @table2 values
(1 ,'Company A'),
(2 , 'Company B'),
(3 , 'Company C'),
(4 , 'Company D')
;with cte as
(
select
t1.ID_Sender, t1.Dates, t2.tags
from @table1 t1
join
@table2 t2 on t1.ID_Sender = t2.id
)
select tags, MAX(dates) as dates from cte group by tags
答案 2 :(得分:0)
首先使用'公司B'更改您的架构。在B表中的ID
这是我的代码:
Select B.Tags, max(A.Date) as 'Date'
from A, B
where B.ID = A.ID_Sender
group by B.Tags