在不同条件下计算所有相同的列并获得最大的列

时间:2017-10-16 06:33:53

标签: mysql sql

我有一个关于如何在不同条件下计算所有相同列的问题。 例如,我有一组地方,每个地方都包含这样的时间

+---------+----------------------+
|pTimeslot|pTimeslotPlace        |
|09:30:00 |shifen waterfall park |
|12:30:00 |shifen waterfall park |
|09:30:00 |shifen water fall park|
|09:30:00 |Taipei Ryo Hotel      |
|17:30:00 |Taipei Ryo Hotel      |
|09:30:00 |shifen water fall park|
+---------+----------------------+

我想计算特定时段的所有地方(早上,下午,晚上都是这样的),我试过这段代码:

SELECT pTimeslotPlace, 
SUM(pTimeslot >= '07:00:00' AND pTimeslot <= '11:59:00') Morning, 
SUM(pTimeslot >= '12:00:00' AND pTimeslot <= '16:59:00') Afternoon,
 SUM(pTimeslot >= '17:00:00' AND pTimeslot <= '18:59:00') Evening, 
SUM(pTimeslot >= '19:00:00' AND pTimeslot <= '03:59:00') Night,
 SUM(pTimeslot >= '04:00:00' AND pTimeslot <= '06:59:00') EarlyMorning 
FROM planTime
WHERE pTimeslotPlace = 'shifen waterfall park';

结果如下:

+---------------------+--------+---------+--------+-------+------------+
|pTimeslotPlace       |Morning |Afternoon|Evening |Night  |EarlyMorning|
|shifen waterfall park|3       |1        |0       |0      |0           |
+---------------------+--------+---------+--------+-------+------------+

问题在于:

  • 如何在所有&#p; pTimeslotPlace&#39;中获得此类结果?无 只有一个地方?

  • 如何获得最大数量的上午或下午或晚上或晚上或提前早晨?在这个例子中,我想只获得Morning,因为它是最大的一个。

谢谢

3 个答案:

答案 0 :(得分:1)

Select pTimeslotPlace, 
       Case Greatest(Morning, Afternoon, Evening, Night, EarlyMorning)
       WHEN Morning then 'MORNING'
       WHEN Afternoon then 'Afternoon'
       WHEN Evening then 'Evening'
       WHEN Night then 'Night'
       WHEN EarlyMorning THEN 'EarlyMorning'
       END As GreatestTime
From (
SELECT pTimeslotPlace, 
  SUM(pTimeslot >= '07:00:00' AND pTimeslot <= '11:59:00') Morning, 
  SUM(pTimeslot >= '12:00:00' AND pTimeslot <= '16:59:00') Afternoon,
  SUM(pTimeslot >= '17:00:00' AND pTimeslot <= '18:59:00') Evening, 
  SUM(pTimeslot >= '19:00:00' AND pTimeslot <= '03:59:00') Night,
  SUM(pTimeslot >= '04:00:00' AND pTimeslot <= '06:59:00') EarlyMorning 
FROM planTime
group by  pTimeslotPlace )

答案 1 :(得分:0)

获取所有不同地方的价值,您可以使用分组

SELECT pTimeslotPlace, 
  SUM(pTimeslot >= '07:00:00' AND pTimeslot <= '11:59:00') Morning, 
  SUM(pTimeslot >= '12:00:00' AND pTimeslot <= '16:59:00') Afternoon,
  SUM(pTimeslot >= '17:00:00' AND pTimeslot <= '18:59:00') Evening, 
  SUM(pTimeslot >= '19:00:00' AND pTimeslot <= '03:59:00') Night,
  SUM(pTimeslot >= '04:00:00' AND pTimeslot <= '06:59:00') EarlyMorning 
FROM planTime
group by  pTimeslotPlace  ; 

答案 2 :(得分:0)

SELECT pTimeslotPlace, 
  SUM(pTimeslot >= '07:00:00' AND pTimeslot <= '11:59:00') Morning, 
  SUM(pTimeslot >= '12:00:00' AND pTimeslot <= '16:59:00') Afternoon,
  SUM(pTimeslot >= '17:00:00' AND pTimeslot <= '18:59:00') Evening, 
  SUM(pTimeslot >= '19:00:00' AND pTimeslot <= '03:59:00') Night,
  SUM(pTimeslot >= '04:00:00' AND pTimeslot <= '06:59:00') EarlyMorning 
FROM Test
group by  pTimeslotPlace order by morning desc; 

将早上更改为您想要的任何列最大