我在sql server中有两个表。
表:1
No Items
1 70
2 72
3 74
表:2
Name Type date
abc 70 12/12/2013 01:10
xyz 70 12/12/2013 10:10
bcd 74 10/12/2013 08:10
efg 74 10/12/2013 09:10
jkl 70 01/01/2012 23:10
现在我想要以下结果:
结果:
Chk Name Type Date
1 xyz 70 12/12/2013 10:10
1 efg 74 10:12/2013 09:10
0 abc 70 12/12/2013 01:10
0 bcd 74 10/10/2013 08:10
0 jkl 70 01/01/2012 23:10
我希望表格中每种类型的最新条目:顶部为1,表格中的chk = 1:结果表中为2。
现在我想写sql查询来找出上面的结果。任何人都可以帮我写同样的SQL查询吗?
答案 0 :(得分:0)
的内容
SELECT t1.No AS Chk, t2.Name, t2.Type, t2.date AS [Date]
FROM Table1 t1 INNER JOIN Table2 t2 ON t1.Items = t2.Type
GROUP BY t1.No, t2.Name, t2.Type, t2.date
ORDER BY t1.No DESC
(实际上我没有在Mgmt Studio中自己输入这个,所以可能有些“关闭”)
答案 1 :(得分:0)
要计算chk
列,您需要查看表之间是否匹配。一个好方法是使用left outer join
和一些case
逻辑:
select (case when t1.no is NULL then 0 else 1 end) as Chk,
t2.name, t2.type, t2.date
from table2 t2 left outer join
table1 t1
on t1.type = t2.items
order by 1, date desc
答案 2 :(得分:0)
试试这个:
WITH Tbl
AS ( SELECT ROW_NUMBER() OVER ( PARTITION BY T1.Items ORDER BY date Desc) Row
FROM Table1 T1
INNER JOIN Table2 T2 ON T1.Items = T2.Type
)
SELECT CASE Row
WHEN 1 THEN 1
ELSE 0
END chk ,
Name ,
Type ,
Date
FROM Tbl