使用case语句检查列

时间:2017-07-10 23:08:14

标签: sql-server if-statement case

我在SQL Server 2012中有一个包含以下列的表:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

我想创建一个case语句来检查这个列ID YEARNBR ----------- 1 2016 2 2015 3 2014 4 2013 1 2015 1 2014 2 2016

YEARNBR

如果我的专栏(case when yearNBR = 2017 and YearNBR = 2016 and YearNBR = 2015 and yearNBR = 2014 then 1 else 0 end) 将包含2016年,2015年和2014年,并且我将按ID进行分组,那么我希望另一个名为YEARNBR的列包含该值1。

2014Through2016

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

只需使用条件聚合:

select id,
       max(case when yearnbr in (2014, 2015, 2016) then 1 else 0 end) as yr_2014_2016,
       max(case when yearnbr = 2016 then 1 else 0 end) as yr_2015
from t
group by id;

答案 1 :(得分:0)

创建一个sameple表:

CREATE TABLE yearz(
  id int,
  yearnbr int
)

INSERT INTO yearz (id,yearnbr)
VALUES 
(1,2016),
(2,2015),
(3,2014),
(4,2013),
(1,2015),
(1,2014),
(2,2016)

使用pivot获取结果:

select id, [2014] as '2014through2016', [2015] as '2015through2016', [2016]
from 
(
  select id, yearnbr
  from yearz
) src
pivot
(
  count(yearnbr)
  for yearnbr in ([2014], [2015], [2016])
) piv;

<强>结果:

id          2014through2016 2015through2016 2016
----------- --------------- --------------- -----------
1           1               1               1
2           0               1               1
3           1               0               0
4           0               0               0

<强>建议 你应该学习如何use PIVOT and UNPIVOT它们非常有用。欢迎来到StackOverflow。如果您发现此或任何其他答案有用,请将其标记为解决方案。这样,它将有助于社区和其他程序员在未来遇到与您相同的问题。干杯!

答案 2 :(得分:0)

select id, sum(yr_2014_2016) as yr_2014_2016, sum(yr_2015_2016) as yr_2015_2016, sum(yr_2016) as yr_2016
from 
(
select id
, (case when yearnbr in (2014, 2015, 2016) then 1 else 0 end) as yr_2014_2016
, (case when yearnbr in (2015, 2016) then 1 else 0 end) as yr_2015_2016
, (case when yearnbr = 2016 then 1 else 0 end) as yr_2016
from t;
)
y
group by Id