在我的一个db表中,有一列FinalDate
将存储日期,数据类型不是datetime
而是varchar
。我想写一个查询,我可以选择不同的FinalDate
和分组/显示,如Jun 2012
,Jul 2012
。
FinalDate
列的值如下所示:
20120213
20120225
20120218
20120306
20120320
那么,我如何编写一个查询来选择FinalDate
的不同内容并将其显示在:
Feb 2012
Mar 2012
答案 0 :(得分:1)
Declare @a table (d varchar(8))
insert into @a Values ('20120213'),('20120225'),('20120218'),('20120306'),('20120320');
Select FinalDate
from
(
select Distinct
--DateName(Month,d)+' '+CAST(Datepart(yy,d) as Varchar(4)) as FinalDate
SubString(DateName(Month,d),1,3)+' '+CAST(Datepart(yy,d) as Varchar(4)) as FinalDate
,Datepart(yy,d) as yy,Datepart(mm,d) as mm
from
(Select CAST(d as datetime) as d from @a) a
) b
Order by yy,mm
答案 1 :(得分:1)
试试这个 -
<强>查询:强>
DECLARE @temp TABLE (t VARCHAR(8))
INSERT INTO @temp VALUES
('20120213'),
('20120225'),
('20120218'),
('20120306'),
('20120320')
SELECT LEFT(DATENAME(MONTH, t), 3) + ' ' + y
FROM (
SELECT DISTINCT
t = CAST(LEFT(t, 6) + '01' AS DATETIME)
, y = LEFT(t, 4)
FROM @temp
) t
ORDER BY t
<强>输出:强>
Feb 2012
Mar 2012
答案 2 :(得分:0)
尝试以下查询
SELECT
Count (SUBSTRING(CONVERT(char(12), CONVERT(date, StringDate,112),113),4,12)) as counts,
SUBSTRING(CONVERT(char(12), CONVERT(date, StringDate,112),113),4,12) from Employees
group by SUBSTRING(CONVERT(char(12), CONVERT(date, StringDate,112),113),4,12)
输出
counts (No column name)
1 Apr 1992
1 Aug 1992
1 Jan 1994
1 Mar 1994
1 May 1992
1 May 1993
1 Nov 1994
2 Oct 1993
答案 3 :(得分:0)
这是基于CTE的方法。将[[[TABLE_NAME]]]替换为包含FinalDate字段的表的实际名称。我在最终选择中而不是在CTE内部进行了处理,以防止SQL Server在过滤掉的(非seq 1)行上执行处理的任何可能性。
WITH a AS (
SELECT ROW_NUMBER() OVER (PARTITION BY LEFT(FinalDate, 6) ORDER BY FinalDate) seq, FinalDate
FROM [[[TABLE_NAME]]]
) SELECT LEFT(DATENAME(mm, FinalDate), 3) + ' ' + LEFT(FinalDate, 4)
FROM a
WHERE seq = 1