2

我有一个group by YEAR(mydate),MONTH(mydate)

我想选择它们作为一个独特的领域

SELECT SUM(Price),YEAR(mydate) + '/' + MONTH(mydate)
FROM MyTable
GROUP BY YEAR(mydate), MONTH(mydate)

或类似的东西。

mydatesmalldatetime

是否可以?

4

5 回答 5

7

试试这个:

SELECT cast(YEAR(mydate) as CHAR(4))+'/'+cast(MONTH(mydate) as varchar(2))
FROM MyTable
Group by YEAR(mydate),MONTH(mydate)
于 2012-08-03T09:22:34.743 回答
2

您需要将它们转换为字符串

尝试

SELECT convert(varchar(7), mydate ,111)
FROM MyTable 
GROUP BY convert(varchar(7), mydate ,111)
于 2012-08-03T09:22:50.570 回答
0

对于 MS SQL Server 2012,带有前导零:

CAST(YEAR(mydate) AS VARCHAR(4)) + '/' +
RIGHT('00' + CAST(MONTH(mydate) AS VARCHAR(2)), 2)
于 2016-08-03T15:20:19.983 回答
0

这是我的解决方案:) 我需要在 sqlserver 表(列 year_rif 和 month_rif)中获取较旧的日期,以从链接的 oracle 表中插入更新的记录(按月作业在 sqlserver 中镜像 oracle 表)

DECLARE @anno_INIZIO int
DECLARE @mese_INIZIO int

select top(1) @mese_INIZIO= mese_rif,@anno_INIZIO=anno_rif 
 from dbo.ORACLE_BUDGET_MENSILI 
 group by  mese_rif,anno_rif 
 order by max(mese_rif/12+anno_rif) desc

set @anno_inizio=coalesce(@anno_INIZIO ,2016)
set @mese_INIZIO=coalesce(@mese_INIZIO,1)

在第一次导入时,我假设从 2016 年 1 月开始获取数据完整的工作是:

    DECLARE @anno_INIZIO int
    DECLARE @mese_INIZIO int
--get max year/mont avaible in mirrored table
    select top(1) @mese_INIZIO= mese_rif,@anno_INIZIO=anno_rif from dbo.ORACLE_BUDGET_MENSILI group by  mese_rif,anno_rif order by max(mese_rif/12+anno_rif) desc
--
    set @anno_inizio=coalesce(@anno_inizio,2016)
    set @mese_INIZIO=coalesce(@mese_INIZIO,1)
-- query to linked oracle to get into table newer data
    SET @SQL='select * FROM OPENQUERY(ADL_REP,''
    SELECT CODICE_UO,ANNO_RIF,MESE_RIF,ID_CLASSE,BUDGET,ORE_MENSILI_OBIETTIVO FROM ADL.BUDGET_MENSILI where  mese_rif/12+anno_rif > '+convert(varchar(255),@mese_INIZIO/12+@anno_INIZIO)+'
    '')'
    INSERT INTO uat.[dbo].ORACLE_BUDGET_MENSILI EXECUTE sp_executesql @SQL
于 2017-04-05T08:35:47.417 回答
-1
SELECT CAST(DATENAME(yy, mydate) AS CHAR(4)) + '-' + CAST(DATENAME(mm, mydate) AS VARCHAR(2)) 'Date'
 ,SUM(Price)
FROM [My Table]
GROUP BY DATENAME(yy, mydate)
 ,DATENAME(ww, mydate)
于 2016-07-04T06:28:38.943 回答