开发者

mySQL: Quering time-related rows grouped by century?

I am working on a project which features one database table looking like this (structurally, but not datawise - puuh):

year    |  event                               |    category
------------------------------------------------------------
1970    |  S开发者_JS百科omeone ate a cheeseburger          |   food
2010    |  Justin bieber was discovered        |   other
1500    |  Columbus makes 3rd trip to America  |   notable
------------------------------------------------------------

How would I query this table, so that my result is grouped in a per-century way?

2000-century:

2010 - Justin bieber was discovered

1900-century:

1970 - Someone ate a cheeseburger

1500-century:

1500 - Columbus makes 3rd trip to America

Sorry for the cheesy psuedodata :)


MySQL doesn't have a century function, but it does have year, so you basically do:

SELECT whatever
FROM yourtable
WHERE ...
GROUP BY CAST((Year(datetimefield) / 100) AS INTEGER)

Of course, this doesn't take into account that centuries officially start on their year "1", and not on the year "0" (e.g. 1900 is still the 18th century, not 19th). But if you're not a stickler for precision, the simple "divide by 100" method is the quickest/easiest.


SELECT CAST((Year(datetimefield) / 100) AS INTEGER) as century, someotherfields
FROM yourtable
WHERE ...
ORDER BY datetimefield

Is a better aproach to the question I think.

(pseudo code borrowed from Marc B)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜