我有group by YEAR(mydate),MONTH(mydate)
我想将它们选为
这样的唯一字段SELECT SUM(Price),YEAR(mydate) + '/' + MONTH(mydate)
FROM MyTable
GROUP BY YEAR(mydate), MONTH(mydate)
或类似的东西。
mydate
是smalldatetime
。
有可能吗?
答案 0 :(得分:7)
试试这个:
SELECT cast(YEAR(mydate) as CHAR(4))+'/'+cast(MONTH(mydate) as varchar(2))
FROM MyTable
Group by YEAR(mydate),MONTH(mydate)
答案 1 :(得分:2)
您需要将它们转换为字符串
尝试
SELECT convert(varchar(7), mydate ,111)
FROM MyTable
GROUP BY convert(varchar(7), mydate ,111)
答案 2 :(得分:0)
对于MS SQL Server 2012,使用前导零:
CAST(YEAR(mydate) AS VARCHAR(4)) + '/' +
RIGHT('00' + CAST(MONTH(mydate) AS VARCHAR(2)), 2)
答案 3 :(得分: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
答案 4 :(得分:-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)