1

我有一个包含 3 列的非常简单的表:

ID  |  Orders | Code
--------------------
  1 |      11 |  'OK'
  2 |      25 | 'ER1'
  3 |       0 |  'OK'
  4 |      30 | 'ER2'
  5 |      42 |  'OK'

我正在尝试创建存储过程来选择符合我的条件的行:

我需要的是能够选择例如少于 10 个订单或多于 30 个订单的行。

所以对我的程序的示例调用是:

EXEC REPORT1 @code='OK', @orders0_10=1,@ordersMore30=1

这应该返回第 3 行和第 5 行。以下是我目前的程序

CREATE PROCEDURE [dbo].[REPORT1]
(
@code NVARCHAR (5) = '',
@orders0_10 INT = 0,
@orders11_20 INT = 0,
@orders21_30 INT = 0,
@ordersMore30 INT = 0,
)
AS

SET NOCOUNT ON

SELECT TOP 1000
    ROW_NUMBER() OVER (ORDER BY RPT.Nr) AS Lp,
    RPT.ID,
    RPT.Orders,
    RPT.Code
FROM MyData RPT (NOLOCK)
WHERE (@code = '' OR RPT.Code= @code)
AND
--(
   (@orders0_10 = 1 AND RPT.Orders<= 10)
--OR (@orders11_20 = 1 AND (RPT.Orders > 10 AND RPT.Orders <= 20))
--OR (@orders21_30 = 1 AND (RPT.Orders > 20 AND RPT.Orders <= 30))
--OR (@ordersMore30 = 1 AND RPT.Orders > 30)
--)
ORDER BY RPT.Nr
GO

编辑 我会尽量澄清我需要什么。
如果我在这里指定标准:http ://sqlfiddle.com/#!3/25045/19我得到 2 行 (1,3),这是正确的。

如果我将它们更改为:http ://sqlfiddle.com/#!3/25045/21我也打赌 2 行 (2,4),这是正确的。

但如果我这样指定它们:http ://sqlfiddle.com/#!3/25045/22我应该得到以前结果的联合(1,2,3,4):

Sales< 10 OR 20 的行

编辑 我得到了最终的工作版本:http ://sqlfiddle.com/#!3/25045/33 ,希望这对某人有用。

4

2 回答 2

1

您的标准是:

where (@orders0_10 = 0 OR RPT.Orders<= 10) AND
      (@orders11_20 = 1 OR (RPT.Orders > 10 AND RPT.Orders <= 20)) AND
      (@orders21_30 = 1 OR (RPT.Orders > 20 AND RPT.Orders <= 30)) AND
      (@ordersMore30 = 1 OR RPT.Orders > 30)

我认为问题出0在第一行;它应该是1

where (@orders0_10 = 1 OR RPT.Orders<= 10) AND
      (@orders11_20 = 1 OR (RPT.Orders > 10 AND RPT.Orders <= 20)) AND
      (@orders21_30 = 1 OR (RPT.Orders > 20 AND RPT.Orders <= 30)) AND
      (@ordersMore30 = 1 OR RPT.Orders > 30)
于 2013-04-19T10:51:07.940 回答
0

您可以使用COALESCE“技巧”:

SELECT 
    RPT.ID,
    RPT.Orders,
    RPT.Code
FROM MyData RPT 
WHERE COALESCE(@code, RPT.Code) = RPT.Code
AND   COALESCE(@orders0_10, RPT.Orders)   <= RPT.Orders
AND   COALESCE(@ordersMore30, RPT.Orders) >= RPT.Orders

演示

于 2013-04-19T10:11:52.407 回答