在sql中存在vs的情况

时间:2016-03-18 09:12:56

标签: sql sql-server sql-server-2008

我有以下查询

SELECT TOP 10 
    CASE
        WHEN EXISTS (SELECT t1.[Code Article] FROM [Promotion] WHERE t1.datecol BETWEEN [Date Debut Promo] AND [Date Fin Promo])
            THEN 1
        ELSE 0
    END AS test1,
    CASE
        WHEN [Code Article] IN (SELECT [Code Article] FROM [Promotion] WHERE datecol BETWEEN [Date Debut Promo] AND [Date Fin Promo])
            THEN 1
        ELSE 0
    END AS test2
FROM [QlikDataWarehouse].[dbo].[Vente] t1   

结果

enter image description here

为什么我得到test1<> test2? test1和test2之间的差异是什么?它不一样吗?

2 个答案:

答案 0 :(得分:1)

原因很简单,您没有比较第一个子选择中的[Code Article]值。

subselect的正确语法是:

Public Sub it()
    On Error GoTo ErrorTrap
    Dim wkRange As Range
    Dim inputRange As String
    Dim argFormula As String
    this_workbook = "MyWBook.xlsm"
    mySheet = "MySheet"
    ' Important: to make it work it is necessary to use WB+Sheet reference
    inputRange = "[" & this_workbook & "]" & mySheet & "!$C:$C"
    inputRange = MakeR1C1(inputRange)

    Set wkRange = ThisWorkbook.Sheets(mySheet).Range("D15:D25")
    ' D14: starting plot
    For Each C In wkRange
        upBound = C.Value
        lowBound = C.Offset(-1, 0).Value
        argFormula = "COUNT(" & inputRange & ") " & _
                 " - COUNTIF(" & inputRange & " ,"">" & upBound & """) " & _
                 " - COUNTIF(" & inputRange & " ,""<=" & lowBound & """)"
        C.Offset(0, 1).Value = argFormula
        C.Offset(0, 2).Value = "between " & lowBound & " and " & upBound
        C.Offset(0, 3).FormulaR1C1 = "=" & argFormula
    Next

Exit Sub
ErrorTrap:
    Beep
    MsgBox "FAILED" & Chr(13) & _
                    "arg: " & argFormula & Chr(13) & _
                    "Error number: " & Err & Chr(13) & _
                    Error(Err)
End Sub
datecol前面的

t1已被删除,[Code Article]与外表连接。

答案 1 :(得分:0)

我们对您的数据库一无所知,因此很难回答这个问题。

使用indizes和外连接。将您的子选择结果放入临时表,并将其用于exists子句。