列之间的标准之间有多个

时间:2013-04-19 10:01:15

标签: sql tsql sql-server-2005

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

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

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

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

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

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&lt;的行10或20

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

Demo