查询具有两个ID字段的表

时间:2018-10-31 16:18:20

标签: sql access ms-access-2016

我有一个名为Actions的表,带有2个标识符:RefStatus
状态可以是以下任意一项:newdone

  Ref  |  Status  |  Date   
  ---------------------------------- 
   1   |   new    | 10/31/2018   
   1   |   done   | 10/31/2018
   2   |   new    | 10/31/2018

我只想查询new而不是done的动作。在此示例中,查询将仅返回表的第三行。

到目前为止,这是我尝试过的操作,但是我只能执行状态为done的操作:

SELECT [2].[project title], [2].ref, [2].[Date] As [Creation Date]
    FROM (SELECT * From T_ACTIONS Where status = "New") AS [1],  
         (SELECT * From T_ACTIONS Where status = "Done") AS [2]
    WHERE [1].[Project Title] = [Insert a valid : Project Title]
    AND [1].[REF] = [2].[Ref]

我正在使用Access 2016。

3 个答案:

答案 0 :(得分:3)

使用NOT EXISTS

SELECT a.*
FROM Actions a
WHERE Status = 'new' AND
      NOT EXISTS (SELECT 1 FROM Actions a1 WHERE a1.REF = a.REF AND a1.Status = 'Done');

答案 1 :(得分:3)

您可以LEFT JOIN的Actions表访问嵌套的SELECT查询,以检索状态为Done的所有引用,并测试嵌套查询中没有相应记录的记录,例如:< / p>

SELECT a.*
FROM 
    Actions a LEFT JOIN (SELECT b.Ref FROM Actions b WHERE b.Status = 'Done') t
    ON a.Ref = t.Ref
WHERE
    a.Status = 'New' AND t.Ref IS NULL

答案 2 :(得分:1)

另一种方法使用聚合:

Sub myDup()
    With Worksheets("Sheet3") ' change to your sheet
        Dim rngArr As Variant
        rngArr = .Range(.Cells(1, 1), .Cells(.Rows.Count, 3).End(xlUp)).Value

        Dim outarr As Variant
        ReDim outarr(1 To Application.Sum(Application.Index(rngArr, 0, 3)), 1 To 3)

        Dim k As Long
        k = 1

        Dim i As Long
        For i = LBound(rngArr, 1) To UBound(rngArr, 1)
            Dim j As Long
            For j = 1 To rngArr(i, 3)
                outarr(k, 1) = rngArr(i, 1)
                outarr(k, 2) = rngArr(i, 2) - j + 1
                outarr(k, 3) = rngArr(i, 3)
                k = k + 1
            Next j
        Next i

        .Range("A1").Resize(UBound(outarr, 1), 3).Value = outarr
    End With
End Sub