需要进出同一行并删除空值

时间:2016-07-12 03:26:17

标签: sql sql-server-2008 null

我有一张名为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

但它没有按预期给我输出。

2 个答案:

答案 0 :(得分:1)

在不知道完整数据的情况下,查询可能会出错,但假设您将始终只有2条记录用于同一AccountId(一条记录intimenull且一条记录在哪里outimenull),您可以在同一个表上使用联接来获取所需的数据;

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并仅过滤了outimenull的记录。然后我根据b将其加入别名intime(其中记录的null值为AccountId)。

该查询假定您始终拥有outimenull的记录,但不一定intimenull,因此使用了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