0

我在 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查询?

4

3 回答 3

0

要计算chk列,您想查看表之间是否存在匹配。一个很好的方法是使用 aleft 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
于 2013-05-15T14:20:38.340 回答
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 中输入这个,所以可能有点“关闭”)

于 2013-05-15T13:56:19.393 回答
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
于 2013-05-16T17:16:33.393 回答