我正在尝试按年分组,但无法做到。我可以获得列数而不是年份。这就是我的尝试。
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
答案 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_contract
和YEAR(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())
在其他数据库引擎中,通常有获取年份部分的方法,或者使用子字符串从时间字符串中获取年份部分。