T-SQL:基于条件

时间:2017-04-19 13:29:43

标签: tsql

有一张桌子:

start | end | zone
------|-----|-----
  1   |  5  |  3
  3   |  6  |  2
  1   |  3  |  1
  4   |  7  |  4

开始和结束代表一个范围。我希望获得价值为4的区域,例如

declare @value as int = 4
select zone from table where @value >= start and @value <= end

,我获得了

3
2
4

,但我只需要预定义范围内的一个区域,例如2或3和3具有优先级,所以如果存在2和3,我希望得到3.因此,区域3是期望的结果我的例子。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

如果它是硬编码的,你可以这样做:

describe('myApp', function () {
  var scope, controller;

  beforeEach(angular.mock.module('myApp'));

  beforeEach(angular.mock.inject(function($controller,$rootScope){
    scope = $rootScope.$new();
    $controller('HomeController', {$scope: scope});
  }));

  it('sets the name', function () {
    expect(scope.name).toBe('Batman');
  });
});

See a live demo on rextester

更新

DECLARE @Value int = 4;

SELECT TOP 1 zone
FROM table
WHERE zone IN (3,2)
AND @Value >= start
AND @Value <= [end] 
ORDER BY CASE WHEN zone = 3 THEN 0 ELSE 1 END

Live demo for updated version

更新2

即使您在评论中写道,由于我的帖子您找到了解决方案,我仍然希望在此处为可能需要它的未来读者发布解决方案:

SELECT TOP 1 CASE WHEN zone IN (3,2) THEN zone ELSE NULL END AS zone
FROM @T
WHERE @Value >= start
AND @Value <= [end] 
ORDER BY CASE WHEN zone = 3 THEN 0 ELSE 1 END