2017-04-11 44 views
0

我需要獲取每張卡的使用日期。如何合併這2個SQL?

我有此SQLS

SELECT distinct card from liq where dateF between '2016-06-09 10:00:00' and '2016-07-09 12:00:00' 

select top 1 * from liq where card = 1129535097095808 order by dateF asc 

在第一個我獲得每張卡的cardNumber。在第二個我必須找到每個人的第一個日期,但我不知道如何合併這兩個SQL,因爲如果我使用卡(查詢1)它將只返回所有這些行中的第一個。

有人可以幫助我嗎?

感謝

+0

添加一些示例表數據和預期的結果 - 以及格式化文本。 – jarlh

+1

標記您正在使用的dbms。 – jarlh

回答

0

最簡單的,但不是最快的:

select top 1 * from liq where card in (SELECT distinct card from liq where dateF between '2016-06-09 10:00:00' and '2016-07-09 12:00:00') order by dateF asc 
0

或嘗試這樣做在一個查詢中,類似這樣的

Select [card], MIN(dateF) over (partition by [card] order by DateF) from liq 
    where dateF between '2016-06-09 10:00:00' and '2016-07-09 12:00:00' 
group by [card] 

所以,你得到一個卡號,並第一次約會被使用

編輯:查詢未測試,但給它一個鏡頭

0

試試這個:

WITH CTE AS(
     SELECT *, 
       ROW_NUMBER() OVER(PARTITION BY CARD ORDER BY dateF) RN 
     from liq 
     where dateF between '2016-06-09 10:00:00' and '2016-07-09 12:00:00' 
) 
SELECT CARD 
FROM CTE 
WHERE RN=1 
0
SELECT top 1 * FROM(SELECT distinct t1.card FROM liq t1 WHERE t1.dateF BETWEEN '2016-06-09 10:00:00' AND '2016-07-09 12:00:00') t2, liq t3 WHERE t2.card=t3.card ORDER BY t2.dateF ASC 

試試這個