按特定顺序选择值

时间:2015-12-09 22:49:25

标签: sql sql-server

让我们使用下表作为例子:

 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

    @Override
    public void onDrawerOpened(View drawerView) {

        // TODO: Handle drawer open action here!
    }

    @Override
    public void onDrawerClosed(View drawerView) {

        // TODO: Handle drawer close action here!
    }
};

drawer.setDrawerListener(toggle);
toggle.syncState();

// Sets up navigation view.
ListView navigationListView = (ListView) findViewById(R.id.navigation_list_view);
NavigationMenuListAdapter navigationMenuListAdapter = new NavigationMenuListAdapter(this);

navigationListView.setAdapter(navigationMenuListAdapter);
navigationListView.setOnItemClickListener(this);

我想选择tableId等于1或2的第一个值,如果没有选择任何行,则选择3或4.

我可以使用下面的select语句,但它只涵盖第一个条件:

tableId
1
2
3
4

我应该在查询中添加什么才能使其正常工作?

1 个答案:

答案 0 :(得分:5)

这是一种方法:

SELECT tableId
FROM exampleTable
WHERE tableId IN (1, 2)
UNION ALL
SELECT tableId
FROM exampleTable
WHERE tableId IN (3, 4) AND
      NOT EXISTS (SELECT 1 FROM exampleTable WHERE tableId IN (1, 2));

以下是另一种使用TOP WITH TIES的方法:

select top 1 with ties
from exampleTable
where tableId in (1, 2, 3, 4)
order by (case when tableId in (1, 2) then 1 else 2 end);

top with ties返回行,而order by键是相同的。通过在case中使用order by,您可以保证1和2以及3和4的排序键相同。

相关问题