Select语句SQL 2012中的MaxMin函数

时间:2016-07-28 08:58:25

标签: sql sql-server-2012

我遇到一些问题,使得MAX函数在select语句中工作。请参阅下面的示例数据:

Table 1                   Table 2
Visit_ID Car_ID        Move_ID  Visit_ID  MoveStartDate  MoveEndDate
A          1              1        A      25/07/2016     27/07/2016 
B          2              2        A      28/07/2016     28/07/2016   
C          1              3        B      19/07/2016     22/07/2016 
D          3              4        D      28/06/2016     30/06/2016

我希望我的select语句根据Visit_ID选择最小开始时间和最大开始时间,所以我期待:

Result
Visit_ID   Car_ID  StartDate   EndDate
A           1      25/07/2016  28/07/2016
B           2      19/07/2016  22/07/2016

到目前为止,我已经尝试过在我的select语句中已经有了内连接:

,(MAX (EndDate) WHERE Visit.Visit_ID = Move.Visit_ID) AS End Date

我已经在select中使用第二个select语句查看了其他一些查询,因此你得到的结果如下:

Select Visit_ID, Car_ID ,(Select MAX(EndDate) FULL OUTER JOIN Table 2 ON Table 1.Visit_ID = Table 2.Visit_ID Group By Table 1.Visit_ID) AS End Date

希望我已经提供了足够的信息。

2 个答案:

答案 0 :(得分:1)

如果您还希望结果中的Car_ID = 3:

select t1.Visit_ID, t1.Car_ID, MIN(MoveStartDate), MAX(MoveEndDate)
from table1 t1
  join table2 t2 on t1.Visit_ID = t2.Visit_ID
group by t1.Visit_ID, t1.Car_ID

返回:

SQL>select t1.Visit_ID, t1.Car_ID, MIN(MoveStartDate), MAX(MoveEndDate)
SQL&from table1 t1
SQL&  join table2 t2 on t1.Visit_ID = t2.Visit_ID
SQL&group by t1.Visit_ID, t1.Car_ID;

visit_id      car_id
======== =========== ==================== ====================
A                  1 25/07/2016           28/07/2016
B                  2 19/07/2016           22/07/2016
D                  3 28/06/2016           30/06/2016

                  3 rows found

答案 1 :(得分:1)

我没有检查,但你可以尝试这个

<select name='slPayment'>
    <option>--</option>
    <option " . (($query2['via']=='Cash') ? 'selected="selected"': '') .  "value='Cash'>Cash</option>
    <option " . (($query2['via']=='Bank Transfer') ? 'selected="selected"': '') . " value='Bank Transfer'>Bank Transfer</option>
    <option " . (($query2['via']=='Credit Card') ? 'selected="selected"': '') . " value='Credit Card'>Credit Card</option>
    <option " . (($query2['via']=='Cheque') ? 'selected="selected"': '') . " value='Cheque'>Cheque</option>
    <option " . (($query2['via']=='Others') ? 'selected="selected"': '') . " value='Others'>Others</option>
</select>