如何从这个查询中提取年和月

5uzkadbs  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(283)

我有一个查询来显示基于日期列的每月订单总数。我可以知道如何在月份栏后面加上年份吗?

select DATENAME(MONTH,DATEADD(MONTH, MONTH(<column>) - 1, 0)) AS Month,
    count(*) AS Total_Request
from <table>
group by month(<column>)

xtupzzrd

xtupzzrd1#

我将直接按年份和月份进行聚合,作为单个文本字段:

SELECT
    CONVERT(varchar(7), <column>, 120) AS Year-Month,
    COUNT(*) AS Total_Request
FROM <table>
GROUP BY
    CONVERT(varchar(7), <column>, 120);

如果您真的想要年份和月份的三个字母缩写,您可以尝试:

SELECT
    YEAR(<column>) AS Year,
    LEFT(DATENAME(MONTH, <column>), 3) AS Month,
    COUNT(*) AS Total_Request
FROM <table>
GROUP BY
    YEAR(<column>),
    LEFT(DATENAME(MONTH, <column>), 3);
lo8azlld

lo8azlld2#

在sql server 2012中,您可以使用format函数

SELECT 
     FORMAT( YourColumn, 'yyyy-MMMM')
     ,COUNT(*) AS Total_Request
FROM 
    <table>
GROUP BY 
    FORMAT( YourColumn, 'yyyy-MMMM')

也可以添加区域性作为第三个参数。在sql语法下面:

FORMAT ( value, format [, culture ] )

有关文档,请参阅此处

相关问题