如何为此编写SQL Server查询?

时间:2011-03-15 15:24:40

标签: sql-server sql-server-2005

SELECT 
   [travel], [service], [bus_type], [travelid], [fro_m], [t_o], 
   [dep], [arr], [booking_closed], [discount], [faresleeper], 
   [rating], [seats], [s_no], 
   s1from, s1to, s1rate, 
   s2from, s2to, s2rate, 
   s3from, s3to, s3rate,
   [fare] = CASE 
               WHEN @date BETWEEN s1from AND s1to THEN s1rate 
               WHEN @date BETWEEN s2from AND s2to THEN s2rate 
               WHEN @date BETWEEN s3from AND s3to THEN s3rate 
               ELSE fare 
   END 
FROM 
   a1_volvo 
WHERE  
   ( fro_m = @fro_m ) AND ( t_o = @t_o ) 

上面提到的查询将显示不同日期之间的不同票价......

fare = textbox1.text   
date = label1.text (shows todays dates)
zero =label2.text

日期广告位1

s1from = textbox2.text (choose date here 01-May-2011 )
s1to=textbox3.text ( choose date here 30-May-2011)
s1rate = textbox4.text ( rate between s1from & s1to ) say 400

日期广告位2

s2from = textbox5.text (choose date here 01-jun-2011 )
s3to=textbox5.text ( choose date here 30-Jun-2011)
s2rate = textbox7.text ( rate between s2from & s2to ) say 500

日期广告位3

s3from = textbox8.text (choose date here 01-Jul-2011 )
s3to=textbox9.text ( choose date here 30-Jul-2011)
s3rate = textbox10.text ( rate between s3from & s3to ) say 600

if user select date between s1from - s1to then fare= s1rate
if user select date between s2from - s2to then fare= s2rate
if user select date between s3from - s3to then fare= s3rate
  • 如果任何用户在s1之前输入日期,则显示实际票价
  • 如果任何用户输入s3到date之后的日期,则会显示label2.text

在这种情况下如何编写选择查询..

1 个答案:

答案 0 :(得分:1)

SELECT
    [travel], [service], [bus_type], [travelid], [fro_m], [t_o],
    [dep], [arr], [booking_closed], [discount], [faresleeper],
    [rating], [seats], [s_no], s1from, s1to,
    s1rate, s2from, s2to, s2rate, s3from, s3to, s3rate,
    CASE
        WHEN @date < s1from THEN fare
        WHEN @date BETWEEN s1from AND s1to THEN s1rate
        WHEN @date BETWEEN s2from AND s2to THEN s2rate
        WHEN @date BETWEEN s3from AND s3to THEN s3rate
        ELSE NULL
    END AS [fare]
FROM a1_volvo
WHERE
    ( fro_m = @fro_m ) AND ( t_o = @t_o ) 

如果日期在s3to之后,您还不清楚要返回的内容,我只需要NULL,因为它很容易测试。此外,如果您在SQL中执行案例逻辑,那么您可能不需要返回该逻辑中涉及的所有值(s1froms1tos1rates2froms2tos2rates3froms3tos3rate