SQL其中1列包含两列某些数据

时间:2014-10-31 07:42:25

标签: sql sql-server subquery

我有一个像

这样的查询
select * 
from Datatable 
where A in  (select A 
             from(subselect Q) 
  and B in (select B from(subselect Q)

但这不会像我想要的那样。

在我的结果中,A和B必须在同一行,但我无法弄清楚如何做到这一点。

编辑:

数据表:
KundeVersionID,Zeitpunkt,KundeID
16,2014-08-05 18:31:10.317,10;
17,2013-11-27 16:26:53.980,11

select * from Datatable
 where (Zeitpunkt  in (select Zeitpunkt from
        (select KundeID, MAX(Zeitpunkt) as Zeitpunkt from KundeVersion 
           group by KundeID)As Q) 
        and KundeID in(select KundeID 
          from (select KundeID,MAX(Zeitpunkt) as Zeitpunkt 
            from KundeVersion group by KundeID)As Q)) order by KundeID

希望这会有所帮助

1 个答案:

答案 0 :(得分:1)

您可以使子查询看起来像FROM子句中的表:

select
  * --TODO - proper column list
from
  Datatable dt
    inner join
  (select KundeID, MAX(Zeitpunkt) as Zeitpunkt from KundeVersion 
           group by KundeID) q
    on
       dt.KundeID = q.KundeID and
       dt.Zeitpunkt = q.Zeitpunkt