我有一张名为alfa的桌子
intime | outime | Accountid |
-------------------------------------------------------------------------------------------------
2016-06-23 06:53:00.000 | 2016-06-23 17:04:00.000 | 1234 |
我期待输出像
select * from alfa
where intime is not null
and exists
(select * from alfa as a
where a.accountid=alfa.accountid
and out is not null)
我正在尝试运行此查询:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
If Batch_Scanner_Dialog.IsDisposed Then
Dim Batch_Scanner_Dialog As New CheckoutBatchScanner
AddHandler Batch_Scanner_Dialog.Scanned_Item, AddressOf Recieve_Scaned_Object
Batch_Scanner_Dialog.Show()
Else
Batch_Scanner_Dialog.Show()
End If
End Sub
但它没有按预期给我输出。
答案 0 :(得分:1)
在不知道完整数据的情况下,查询可能会出错,但假设您将始终只有2条记录用于同一AccountId
(一条记录intime
为null
且一条记录在哪里outime
为null
),您可以在同一个表上使用联接来获取所需的数据;
SELECT a.intime, b.outime, a.AccountId
FROM alfa a
LEFT JOIN alfa b ON a.AccountId = b.AccountId
AND CONVERT(date, a.intime) = CONVERT(date, b.outime)
AND b.intime is null
WHERE a.outime is null
我在这里使用别名a
并仅过滤了outime
值null
的记录。然后我根据b
将其加入别名intime
(其中记录的null
值为AccountId
)。
该查询假定您始终拥有outime
为null
的记录,但不一定intime
为null
,因此使用了LEFT JOIN
。
更新:根据评论,我向JOIN
添加了另一个条件 - 仅从intime
加入日期,仅从outime
加入日期。提取日期的方法仅基于this answer。
答案 1 :(得分:0)
请查看这是否是您所需要的。
SELECT MIN(t.intime),MAX(isnull(t.outime,0)),accountid
FROM alfa t
group by t.accountid