我需要获得每张卡的第一个日期。
我有这个SQL
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,因为如果我使用'在(query1)中,它只返回所有这些行中的第一行。
有人可以帮我吗?
由于
答案 0 :(得分: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
答案 1 :(得分: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]
所以你得到了一个卡号,并且使用了第一个日期
编辑:查询未经过测试,但试一试
答案 2 :(得分: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
答案 3 :(得分: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
试试这个