drbouzlxb92333332 2015-05-30 03:58
浏览 9
已采纳

如何根据两行条件选择列值?

Name      Username    Day worked  Time period  
----------------------------------------------
John Doe  john        Sunday      8
Tom       tom         Monday      10
Jane Doe  jane        Tuesday     5
John Doe  john        Friday      9

Query:

SELECT username FROM table WHERE (day_worked='Sunday' AND time_period>5) AND (day_worked='Friday' and time_period>8)

Here I am applying conditions for two columns, user who worked on Sunday more than 5 hours and Friday more than 8 hours. So obviously John Doe (Username: john) meets the condition and it should be outputted.

However this does not return anything. May be the logic I am using is wrong. Any ideas?

  • 写回答

3条回答 默认 最新

  • dongya4089 2015-05-30 04:38
    关注

    You can do this by a bit of cross-tabulation magic. First off, cross tabulate all of your users by Sunday and Friday:

    SELECT
      username,
      SUM(CASE WHEN `Day worked` = 'Sunday' THEN `Time Period` END) As Sunday,
      SUM(CASE WHEN `Day worked` = 'Friday' THEN `Time Period` END) AS Friday
    FROM table
    GROUP BY username
    

    This query will yield the following:

    username  Sunday  Friday
    --------  ------  ------
    jane      NULL    NULL
    john      8       9
    tom       NULL    NULL
    

    By pushing this result down into a subquery you can easily pick out who worked more than 5 hours on Sunday and more than 8 hours on Friday:

     SELECT username
     FROM (
       SELECT
         username,
          SUM(CASE WHEN `Day worked` = 'Sunday' THEN `Time Period` END) As Sunday,
          SUM(CASE WHEN `Day worked` = 'Friday' THEN `Time Period` END) AS Friday
        FROM table
        GROUP BY username
      ) SunFri
    WHERE SunFri.Sunday > 5 AND SunFri.Friday > 8
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本