我有一个事件和日期列表以及它们,yyyy-mm-dd然后是一个类别。
我需要按一年中的每个月的类别(超速罚单,DUI等)订购。
这就是两列的样子
2002-12-28 No Driver License
2002-12-28 Hazardous Violations
2002-12-28
2002-12-28 Speeding
2002-12-28 DUI
2002-12-28 Reckless Driving
2002-12-28
2002-12-28 Speeding
这是我到目前为止所拥有的
SELECT
[Date]
,[categoryId]
= (SELECT tertiary FROM [MSDAS].[dbo].[activity_categories] AS C
WHERE C.categoryId = A.categoryId)
,[value]
FROM [MSDAS].[dbo].[hp_activities] AS A
JOIN [MSDAS].[dbo].[workdays] AS W ON W.workdaysId = A.workdaysId
WHERE W.date IS NOT NULL
AND W.date >= '2002/1/1'
ORDER BY Date
答案 0 :(得分:1)
SELECT innerSelect.dateMonth
, innerSelect.dateYear
FROM (SELECT (MONTH(yourTable.Date)) AS dateMonth
, YEAR(yourTable.Date) AS dateYear
FROM yourTable) AS innerSelect
GROUP BY innerSelect.dateMonth, innerSelect.dateYear
答案 1 :(得分:0)
http://sqlfiddle.com/#!9/badf7/1
SELECT sum(id),
category,
year(t) y,
month(t) m
FROM table
GROUP BY category, y, m;
我在添加样本数据之前做了准备,所以类别是数字的(无论如何要将其标准化,有一个单独的类别表并且只保留category_id)
这就是我按月和按年分组理解的内容。
编辑:在问题从mysql重新绑定到sql server之前回答