按年分组在sql中

时间:2014-02-24 10:30:32

标签: sql sql-server

我正在尝试按年分组,但无法做到。我可以获得列数而不是年份。这就是我的尝试。

 select  t_contract ,
    sum(CASE t_contract when '18' then 1 else 0 end) as XL, 
    sum(CASE t_contract when '01' then 1 else 0 end) as VC,
    sum(CASE t_contract when '75'    then 1 else 0 end) as AN,
    sum(CASE t_contract when '48'    then 1 else 0 end) as CS

    from icps.dbo.tickets
    WHERE 
     t_date_time_issued >= DATEADD(year, -6, GETDATE())
        GROUP BY contract

..但我想添加年份..我有t_date_time _issued列。 我的另一个问题是我有一个名为t_zone_name的列,我想要总结t_zone_anme like '%ICeland%'我试过的所有行:

 sum(CASE t_zone_name like '%ICeland%'    then 1 else 0 end) as ICELAND

但我在声明中收到错误,比如......先谢谢。

LIKE

YEAR XL  VC  AN  CS total 
2010 50  50  50  50  200
2011  5   5   5  5   20

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

SELECT t_contract, YEAR(t_date_time_issued) As Yr, SUM(CASE WHEN t_zone_name like '%ICeland%'  THEN 1 ELSE 0 END) AS ICELAND

SUM(CASE t_contract when '18' then 1 else 0 end) as XL, 
SUM(CASE t_contract when '01' then 1 else 0 end) as VC,
SUM(CASE t_contract when '75'    then 1 else 0 end) as AN,
SUM(CASE t_contract when '48'    then 1 else 0 end) as CS

FROM icps.dbo.tickets
WHERE YEAR(t_date_time_issued) >= (YEAR(GetDate()) - 6)
GROUP BY t_contract, YEAR(t_date_time_issued)   

您可能需要更改t_contractYEAR(t_date_time_issued)的顺序,具体取决于您首先要应用的分组。

根据@ray的建议,我已将DATEPART(yyyy, t_date_time_issued) >= DATEPART(yyyy, DATEADD(year, -6, GETDATE()))替换为year(t_date_time_issued) >= (year(GetDate()) - 6)

答案 1 :(得分:0)

如果你想按年份分组,在sql server中,你可能

GROUP BY DATEDIFF(year,t_date_time_issued, GETDATE())

在其他数据库引擎中,通常有获取年份部分的方法,或者使用子字符串从时间字符串中获取年份部分。