两个最小值之间的SQL

时间:2015-08-07 09:20:16

标签: sql sql-server between

如果我必须在SQL Server中编写此查询:

SELECT * 
FROM Table1 
WHERE data BETWEEN interval1 AND interval2
    如果interval1> ='2014-1-1',则
  • fld1fld1,否则为'2014-1-1'
  • interval2 fld2 fld2如果Ksdt_TP022_Data BETWEEN (SELECT CASE WHEN sdt_TP019_InizioVal < '2014-1-1' THEN '2014-1-1' ELSE sdt_TP019_InizioVal END as b from TP022_Quarto) AND (SELECT CASE WHEN sdt_TP019_Fineval > '2014-12-31' THEN '2014-12-31' WHEN sdt_TP019_Fineval IS NULL THEN '2014-12-31' ELSE sdt_TP019_Fineval END as a from TP022_Quarto) &lt; ='''2014-12-31',否则为'2014-12-31'

如何在不使用变量的情况下编写它?

我试试

<?php foreach($products as $product){ 
    echo "<pre>"; print_r($product); // line 1
?>
<tr>// line 2
    <td align="center"><?php echo $product['name']; ?></td>
    <td align="center"><?php echo $product['sku']; ?></td>
    <td align="center"><?php echo $product['status']; ?></td>
    <td align="center"><?php echo $product['date_time']; ?></td>
    <td align="center">Edit / Delete</td>               
</tr>
<?php }  exit;?>

但是出现编译错误

3 个答案:

答案 0 :(得分:2)

试试这个

select * from Table1 
WHERE data between 
case when fld1 < '20140101' then '20140101' else fld1 end and 
case when fld2 >'20141231 then '20141231' else fld2 end 

答案 1 :(得分:1)

SELECT * 
FROM 
  Table1 
WHERE
  data BETWEEN interval1 AND coalesce(interval2, '2014-12-31')
  and data between '2014-1-1' and '2014-12-31'

答案 2 :(得分:0)

几乎同样的问题被问到here

简而言之,您可以使用UDF(用户定义的函数)或CASE语句。