我不确定在下面的SQL查询中应该写什么来显示'date'列,如下所示:“month-year” - “9-2011”。
SELECT MONTH(date) + '.' + YEAR(date) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY MONTH(date), YEAR(date)
所以,我想要做的是将第一列中的数据更改为显示月份和年份而不是仅显示月份。
答案 0 :(得分:136)
SELECT CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4)) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4))
或者正如@ 40-Love所提到的,你可以使用前导零投射:
GROUP BY
CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2)
答案 1 :(得分:12)
我猜是MS SQL,因为它看起来像MS SQL语法。
所以你应该把组内行与select ex:
中的相同Select MONTH(date)+'-'+YEAR(date), ....
...
...
...
group by MONTH(date)+'-'+YEAR(date)
答案 2 :(得分:5)
如果我理解正确的话。为了按要求对结果进行分组,Group By子句需要与select语句具有相同的表达式。
GROUP BY MONTH(date) + '.' + YEAR(date)
要将日期显示为“月 - 日”格式,请更改“。”至 '-' 完整的语法就是这样的。
SELECT MONTH(date) + '-' + YEAR(date) AS Mjesec, SUM(marketingExpense) AS
SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY MONTH(date) + '.' + YEAR(date)
答案 3 :(得分:2)
Yet another alternative:
Select FORMAT(date,'MM.yy')
...
...
group by FORMAT(date,'MM.yy')
答案 4 :(得分:1)
在postgresql中,我可以使用日期格式函数(to_char)编写类似的查询,并按日期分组:
SELECT to_char (datum, 'MM-YYYY') AS mjesec
FROM test
GROUP BY datum
ORDER BY datum;
这样的事情肯定也可以用SQL-Server,不是吗?
答案 5 :(得分:1)
上面的SQL Server 2012,我更喜欢使用format()函数,更加简化。
SELECT format(date,'MM.yyyy') AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY format(date,'MM.yyyy')
答案 6 :(得分:0)
您可以尝试乘以调整年份和月份,以便它们成为一个数字。根据我的测试,它的运行速度比format(date,'yyyy.MM')
快得多。我更喜欢将前一年用于分类目的。从MS SQL Server Express 12.0版创建的代码。
SELECT (YEAR(Date) * 100) + MONTH(Date) AS yyyyMM
FROM [Order]
...
GROUP BY (YEAR(Date) * 100) + MONTH(Date)
ORDER BY yyyyMM
答案 7 :(得分:0)
对于mariaDB,您可以:
SELECT DATE_FORMAT(date, '%m-%Y')
FROM [Order]
GROUP BY
DATE_FORMAT(date, '%m-%Y')
答案 8 :(得分:-6)
如果您希望保留datetime数据类型的字段,请尝试使用:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order] o
WHERE (idCustomer = 1) AND (o.[date] BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0)
它也很容易按小时,天,周,年改为小组...
我希望它对某人有用,
问候!