douzhu7507 2014-02-19 22:21
浏览 30
已采纳

sql查询计算一个查询中的多个已定义列

I have been looking through this website to try and a) understand my problem better and b) to to find some help to solve it but it seems everything i've seen is slightly different to my problem so im here to ask for some advice please :)

i have the following query

SELECT *, 
(date_end < 1392569012) AS expired, 
(date_start > 1392569012) AS pending, 
(date_end > 1392569012 && date_start <= 1392569012) AS active 
FROM tbl_events AS event 
LEFT JOIN tbl_event_events AS ee ON event.event_id = ee.event_id
WHERE event.event_type = 5 && event.user_id = '".$user->getUserID()."'
ORDER BY expired,pending,active

which determins the status of a listing.

now what i want to do is count the number of active, pending and expired listings

this is my updated query, but it only returns 1 row but the correct sum values?

SELECT *, 
SUM(date_end < 1392569012) AS expiredCount,
SUM(date_start > 1392569012) AS pendingCount, 
SUM(date_end > 1392569012 && date_start <= 1392569012) AS activeCount,              
(date_end < 1392569012) AS expired, 
(date_start > 1392569012) AS pending, 
(date_end > 1392569012 && date_start <= 1392569012) AS active 
FROM tbl_events AS event 
LEFT JOIN tbl_job_events AS jobvent ON event.event_id = jobvent.event_id
LEFT JOIN tbl_job_department AS jdept ON event.event_id = jdept.event_id
LEFT JOIN tbl_departments as dept ON jdept.department_id = dept.department_id 
WHERE event.event_type = 2 && event.user_id = '".$user->getUserID()."'
ORDER BY expired,pending,active 

could someone help me get this working please!

thanks for any help

Luke

  • 写回答

1条回答 默认 最新

  • dqvrlgi3247 2014-02-19 22:24
    关注

    since active will be 1 for that filter and 0 for others, add sum to the active filter to get the count of rows which satisfies that filter.

    SELECT *, ( SELECT  SUM(date_end > 1392569012 && date_start <= 1392569012)
    FROM tbl_events AS event 
    LEFT JOIN tbl_event_events AS ee ON event.event_id = ee.event_id
    WHERE event.event_type = 5 && event.user_id = '".$user->getUserID()."'
    ORDER BY expired,pending,active),
    (date_end < 1392569012) AS expired, 
    (date_start > 1392569012) AS pending, 
    (date_end > 1392569012 && date_start <= 1392569012) AS active 
    FROM tbl_events AS event 
    LEFT JOIN tbl_event_events AS ee ON event.event_id = ee.event_id
    WHERE event.event_type = 5 && event.user_id = '".$user->getUserID()."'
    ORDER BY expired,pending,active
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding