2015-12-22 133 views
1

給定一個數據庫,將表命名爲具有id和created_at字段的用戶。 Id是smallint類型,created_at是datetime類型。想知道每個月註冊的人員。SQL日期時間查詢

我正在使用的數據庫是SQLite。

寫了這個簡單的查詢應該工作,但它會給出一個錯誤。你能幫我解決嗎?

select count(id) as Orders, DATEPART(mm,created_at) AS Ordermonth 
from users 
Group by DATEPART(mm,created_at); 
+0

你有什麼錯誤? –

+2

您的查詢使用SQL Server函數。你的問題被標記爲「mysql」和「sqlite」。難怪你有問題。 –

+0

錯誤我得到..沒有這樣的列:mm ... – user1932914

回答

3

SQLite中的等效會是什麼樣子:

Select count(id) as Orders, strftime('%Y-%m', created_at) AS Ordermonth 
From users 
Group by strftime('%Y-%m', created_at) 
Order by Ordermonth; 

你的代碼看起來像SQL Server代碼。

+0

非常感謝,代碼解決了......但我有一個問題,爲什麼我不能使用datepart函數? – user1932914

+0

@ user1932914。 。 。因爲它在SQLite中不存在。同樣,'strftime()'不存在於除SQLite以外的任何其他數據庫中。 –

+0

非常感謝..我能解決我的問題。 – user1932914