使用In从第二个查询中提取结果

时间:2016-02-01 14:16:12

标签: sql

我有一个存储发票详细信息的数据库。正如您所期望的那样,发票的每个细节都列在数据库中。一些样本信息:

Invoice#     Service_Type    Detail_Code
1234            1               AB
1234            2               DF
1234            5               ER
1235            1               AB
1236            1               AB
1236            2               DF
1237            1               AB
1238            1               AB
1239            1               AB
1239            3               DZ

我想写一个查询来计算客户服务类型为' 1'的服务数量。并且没有DZ或DF的详细代码。所以在这种情况下,我的查询结果将是:

"3"

它将计算发票号码:

1235
1237
1238

我完全没能做到。这是我的疑问:

SELECT Invoice_Number
FROM Invoice_Detail_Tb
WHERE (Invoice_Number IN (SELECT Invoice_Number
                          FROM Invoice_Detail_Tb AS Invoice_Detail_Tb_1
                          WHERE (Service_type = '1')
                            AND (Invoice_Date BETWEEN @startdate AND @enddate)
                            AND (Store_Number = @storenumber)))
  AND (Detail_Code NOT IN ('DF', 'DZ'))

当我运行此查询时,我不断得到" 6"这是service_Type" 1"的服务总数。我错过了什么?

2 个答案:

答案 0 :(得分:0)

一种方法是使用EXCEPT

SELECT Invoice_Number
FROM  Invoice_Detail_Tb
where service_type = '1'
EXCEPT
SELECT Invoice_Number
FROM  Invoice_Detail_Tb
where Detail_Code IN ('DF', 'DZ')

由于您无法使用except,因此可以使用not exists

SQL Fiddle

SELECT Invoice_Number --use count(*) if you only need count
FROM  Invoice_Detail_Tb t
where service_type = '1'
and not exists(select 1 from Invoice_Detail_Tb where invoice_number = t.invoice_number and
               Detail_Code IN ('DF', 'DZ'))

答案 1 :(得分:0)

使用DISTINCT:

时,获取唯一发票号可能非常简单
SELECT DISTINCT
    Invoice_Number
FROM  Invoice_Detail_Tb
WHERE
    Service_type = '1'
    and Detail_Code NOT IN ('DF', 'DZ')
    and Invoice_Date BETWEEN @startdate AND @enddate 
    and Store_Number = @storenumber

对于计数服务:

SELECT 
    Invoice_Number,
    count(*) as services_Count
FROM  Invoice_Detail_Tb
WHERE
    Service_type = '1'
    and Detail_Code NOT IN ('DF', 'DZ')
    and Invoice_Date BETWEEN @startdate AND @enddate 
    and Store_Number = @storenumber
GROUP BY Invoice_Number