dongluobei9359 2015-04-07 12:25
浏览 18

MYSQL记录获取2个日期

Currently i require that if time is before noon for current day, then it should take the item_2 value of prev day for current day only. for others it will take, their proper values.

    id  |   item_1 | item_2 | date
    1       205         3       2015-04-07
    2       215         35      2015-04-06
    3       225         15      2015-04-05
    4       235         315     2015-04-04

Expected result wen time is before noon

    id  |   item_1 | item_2 |   sum |    date
    1       205         35      240     2015-04-07
    2       215         35      250     2015-04-06
    3       225         15      240     2015-04-05
    4       235         31      266     2015-04-04

Expected result wen time is after noon

    id  |   item_1 | item_2 |   sum |    date
    1       205         3       208     2015-04-07
    2       215         35      250     2015-04-06
    3       225         15      240     2015-04-05
    4       235         31      266     2015-04-04

Date and time can be used from php and how to manage for prev and current day record in same query. i tried with sub query, but i think it can be done in other way also.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doulin6761 2015-04-07 13:23
    关注

    In this case you have to use CASE in your query:

    try this:

    SET @time := 'BFNOON';
    SET @date := '2015-04-07 00:00:00';
    
    SELECT id, item_1, item_2, (item_1 + item_2) AS sum_item, dates FROM (
    SELECT id, item_1,
    (CASE
    WHEN (@time = 'BFNOON' AND dates = @date) THEN 
    (
    SELECT item_2 FROM records WHERE dates < @date ORDER BY dates DESC  LIMIT 1
    ) ELSE 
    item_2
    END ) item_2
    , dates 
    
    FROM records ) records
    

    Note: remove declaration and replace @time = 'BFNOON' to check before or after noon and @date with your date value of today

    here sqlfiddle as example : http://sqlfiddle.com/#!9/f5dbe/10

    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)