1

在我的一个数据库表中,有一列FinalDate将存储日期,数据类型不是datetimebut varchar。我想写一个查询,我可以选择 distinctFinalDate和 group/display like Jun 2012, Jul 2012.

该列的值FinalDate如下所示:

20120213  
20120225  
20120218  
20120306  
20120320

那么,我如何编写一个查询来选择不同的FinalDate并将它们显示在:

Feb 2012  
Mar 2012
4

4 回答 4

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
于 2013-06-06T09:58:12.037 回答
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
于 2013-06-06T10:06:03.887 回答
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 
于 2013-06-06T10:15:55.800 回答
0

这是基于 CTE 的方法。将 [[[TABLE_NAME]]] 替换为包含 FinalDate 字段的表的实际名称。我在最终选择中而不是在 CTE 内部进行了处理,以防止 SQL Server 对过滤掉的(非序列 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
于 2013-06-10T05:14:01.370 回答