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

时间:2014-02-19 22:21:29

标签: php mysql sql database mysqli

我一直在浏览这个网站尝试和a)更好地理解我的问题和b)找到一些帮助解决它但似乎我所看到的一切与我的问题略有不同所以我在这里要求一些建议请:)

我有以下查询

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

确定列表的状态。

现在我要做的是计算有效,待定和过期的商品数量

这是我更新的查询,但它只返回1行但是正确的和值?

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 

有人可以帮我解决这个问题!

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

因为对于该过滤器,active为1,对于其他过滤器为0,所以将sum添加到活动过滤器以获得满足该过滤器的行数。

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