我正在寻找如何过滤查询的数据结果,如果某个位置使用特殊的where子句。我很难用文字来解释我想做什么,但这是我的例子:
我有一个查询从一系列位置提取结果:
Select a.Location, a.Invoice_date, a.service, a.QTY, b.user
From Invoice_detail as a inner join Invoice_tb as b on
a.invoice_number = b.invoice_number and a.location = b.location
where invoice_date between @startdate and @enddate and Not (a.location = 1 and a.service = 1)
order by a.location
这给了我以下输出:
Location Invoice Date Service QTY User
1 1/2/16 1 1 Tim
1 1/2/16 1 1 Bob
1 1/2/16 1 1 Tim
1 1/2/16 2 1 Bob
1 1/2/16 3 1 Bob
2 1/2/16 1 1 Tim
2 1/2/16 2 1 Bob
2 1/2/16 4 1 Tim
3 1/2/16 1 1 Bob
3 1/2/16 6 1 Tim
3 1/2/16 1 1 Bob
如果位置为“1”,我想不返回服务'1'。但我想要将服务1退回到任何其他位置。所以我希望我的输出看起来像这样:
Location Invoice Date Service QTY User
1 1/2/16 2 1 Bob
1 1/2/16 3 1 Bob
2 1/2/16 1 1 Tim
2 1/2/16 2 1 Bob
2 1/2/16 4 1 Tim
3 1/2/16 1 1 Bob
3 1/2/16 6 1 Tim
3 1/2/16 1 1 Bob
答案 0 :(得分:1)
在AND NOT(Service = 1 AND Location = 1)
条件中添加WHERE
:
SELECT
a.Location,
a.Invoice_date,
a.service,
a.QTY,
b.[user]
FROM Invoice_detail AS a
INNER JOIN Invoice_tb AS b
ON a.invoice_number = b.invoice_number
AND a.location = b.location
WHERE
invoice_date BETWEEN @startdate AND @enddate
AND NOT(a.service = 1 AND a.Location = 1)
ORDER BY a.location