2016-01-13 45 views
0

我用下面的示例行的SQLite數據庫與{ID,溫度,描述,TIME_STAMP列:SQLite的:子查詢組由最大數

1 45 Clear 2016-01-13 10:24:17 
2 45 Clear 2016-01-13 10:24:41 
3 45 Clear 2016-01-13 10:24:41 
4 45 Rain 2016-01-13 10:24:41 
5 46 Clear 2016-01-13 10:38:29 
6 46 Clear 2016-01-13 10:38:53 
7 46 Clear 2016-01-13 10:39:08 
8 46 Clear 2016-01-13 10:39:08 

我對他們的運行此查詢到他們組由時間間隔和天氣描述:

SELECT AVG(current_temperatures) AS temp_avg, 
      CASE WHEN strftime('%M', time_stamp) < '30' 
      THEN strftime('%H', time_stamp) 
      ELSE strftime('%H', time_stamp, '+1 hours') END as hour, 
      current_weather_description, 
      count(*) as counter 
      FROM weather_events 
      GROUP BY strftime('%H', time_stamp, '+30 minutes'), current_weather_description 
      order by hour desc 

,結果如下{ROW_NUM,temp_avg,小時,current_weather_description,計數器}:

​​

我的問題是我如何通過最大計數器子查詢每個小時和組。所以最終我想得到結果:

"46.0" "11" "Clear" "4" 
"45.0" "10" "Clear" "3" 

我是新來的SQL和SQLite。所有數據來自同一張表。 另外,由於查詢的溫度是平均值,它如何選擇我要求它選擇的其餘列?例如,如果你選擇time_stamp,你會發現它是來自數據庫的一個特定的time_stamp。它是否隨機選擇要選擇的列?

回答

0

你的sql查詢得到正確的輸出。您已按照half hour time intervalsweather description對行進行分組。 10:00 time interval有兩種不同的天氣:「清除」和「雨」,以及10:30 time interval的一個天氣:「清除」。如果您將從GROUP BY子句中移除weather_description列,則只會獲得兩行。

common table expressions的解決方案只顯示時間間隔中最常發生的天氣描述。

;WITH temp_data AS(
    SELECT AVG(current_temperatures) AS temp_avg, 
      CASE WHEN strftime('%M', time_stamp) < '30' 
      THEN strftime('%H', time_stamp) 
      ELSE strftime('%H', time_stamp, '+1 hours') END as hour, 
      current_weather_description, 
      count(*) as counter 
    FROM weather_events 
    GROUP BY strftime('%H', time_stamp, '+30 minutes'), 
      current_weather_description 
) 

SELECT T1.* FROM temp_data AS T1 
WHERE T1.counter = (SELECT MAX(counter) FROM temp_data AS T2 
        WHERE T2.hour = T1.hour) 
+0

當我這樣做,它然後輸出「雨」的描述,我不希望,因爲它是在該時間間隔基本清晰的 –

+0

因此,這意味着你要顯示的天氣說明出現這種情況往往比別人,對嗎? – fabulaspb

+0

是的,它確實@fabulaspb –