2013-08-28 55 views
2

我想要做的是:在出生日期之後對數據庫中的人進行排序(nvarchar,不是日期類型)日期是以這種字符串格式:dd-MM-yyyy和Sort,我的意思是返回所有人,但在出生日期之後排序,填充datagridview。如何使sql查詢將數據庫字符串拆分爲3個不同的部分並進行比較?

我有一個列出生日期,這是nvarchar。我想在sql查詢中存儲3個變量的日期,月份和年份,並測試它們以便將它們排序。

我的嘗試是:

SELECT SUBSTRING(date_of_birth,0,2) FROM people AS zi; 
SUBSTRING(date_of_birth,3,2) AS luna 
SUBSTRING(date_of_birth,6,4) AS an 
SELECT [id], [specie], [sex], [date_of_birth], [greutate] FROM [people] WHERE 

,但我真的不知道如何從現在開始看着辦吧......

+0

爲什麼不分析它作爲一個日期,如果它真的是約會?請參閱:'STR_TO_DATE()'在這裏:http://stackoverflow.com/questions/3296725/parse-date-in-mysql – 2013-08-28 20:50:20

回答

4
SELECT 
    [id], [specie], [sex], [date_of_birth], [greutate], 
    SUBSTRING(date_of_birth,6,4) AS [an], 
    SUBSTRING(date_of_birth,3,2) AS [luna], 
    SUBSTRING(date_of_birth,0,2) AS [zi] 
FROM 
    [people] 
ORDER BY 
    SUBSTRING(date_of_birth,6,4), 
    SUBSTRING(date_of_birth,3,2), 
    SUBSTRING(date_of_birth,0,2) 

許多RDBMS也讓這個...

SELECT 
    [id], [specie], [sex], [date_of_birth], [greutate], 
    SUBSTRING(date_of_birth,6,4) AS [an], 
    SUBSTRING(date_of_birth,3,2) AS [luna], 
    SUBSTRING(date_of_birth,0,2) AS [zi] 
FROM 
    [people] 
ORDER BY 
    [an], [luna], [zi] 
+0

「許多RDBMS也允許這...」(是的,甚至MySQL) – 2013-08-28 20:51:39

+0

會改變我想按他們的年齡命令人們?我應該計算什麼或...? –

+0

@HoreaMihuţ - 由DoB訂購在數學上與按年齡排序相同...更老的人有更久以前的DoB ... – MatBailie

0

試試這個..

SELECT 
[id], [specie], [sex], [date_of_birth], [greutate] 
From 
[People] 
ORDER BY 
Convert(DateTime, date_of_birth, 105) Asc 

由列轉換爲DateTime類型105,你可以得到它的「DD-MM-YYYY」的格式,因爲它是

粘貼此代碼,並嘗試..

相關問題