【问题标题】:How to write several union select in one select in SQL Server如何在 SQL Server 中在一次选择中编写多个联合选择
【发布时间】:2020-09-02 10:30:30
【问题描述】:

我需要设计一个界面,用户可以选择年份然后月份,年份可能是几年,并且每年可以选择几个月,然后我需要编写一个select语句来检索数据。我可以通过几个选择语句来做到这一点并将它们联合起来。有没有办法一次性写出来?

这个截图显示了我需要设计的界面:

我写的是这样的:

select * 
from yearmonth 
where year = '1390' and month in ('1', '2')
union
select * 
from yearmonth 
where year = '1391' and month in ('3', '4')
union
select * 
from yearmonth 
where year = '1392' and month in ('5')
union
select * 
from yearmonth 
where year = '1393' and month in ('1', '2')

【问题讨论】:

    标签: sql-server select union


    【解决方案1】:

    您可以通过将条件与 OR 运算符组合来做到这一点:

    select * 
    from yearmonth 
    where 
      (year = '1390' and month in ('1', '2'))
      or
      (year = '1391' and month in ('3', '4'))
      or
      (year = '1392' and month in ('5'))
      or
      (year = '1393' and month in ('1', '2'))
    

    对于这些条件,代码可以简化为:

    select * 
    from yearmonth 
    where 
      (year in ('1390', '1393') and month in ('1', '2'))
      or
      (year = '1391' and month in ('3', '4'))
      or
      (year = '1392' and month = '5')
    

    【讨论】:

    • 可以简化 - 但查询是由用户选择驱动的,编写逻辑来检查所有选择的选项以进行优化并非易事。
    • @SM这就是为什么我说对于这些条件...
    猜你喜欢
    • 1970-01-01
    • 2012-03-15
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 2013-12-31
    相关资源
    最近更新 更多