SQL语句 - 使用数字声明多个值

时间:2018-04-06 07:44:04

标签: sql sql-server case

我想从包含值0或1的表生成一个新列。这些值用于指示另一列是否包含在数据库中出现多次的值。

例如:

表:

Attribute 1 
A 
B 
C 
A 
B 
F 
A 
B 

Attribute New
1
1
0
1
1
0
1
1

等等......我已经尝试了CASE和HAVING,但不知怎的,我找不到想要的解决方案。有人有任何想法吗?

非常感谢您的帮助:)

4 个答案:

答案 0 :(得分:1)

子查询上的{p> Group BYCOUNT以及join之后的count大于{1},那么您可以在{{1}上使用CASE表达式条款。

你可以这样试试。

select
  

http://sqlfiddle.com/#!18/ca346/1

答案 1 :(得分:0)

我认为DECODE应该可以工作:

Select a1,
 CASE PAttribute_1 
 WHEN (SELECT COUNT(1) FROM T WHERE a1 = p.a1 ) > 1 THEN 1
ELSE 0
END

答案 2 :(得分:0)

您可以使用许多属性来获取所需的输出

示例数据:

declare @table table (attribute1 varchar(3))

insert @table (attribute1)

select 'A' union all 
 select 'B' union all 
select 'C' union all 
select 'A' union all 
select 'B' union all 
select 'F' union all 
select 'A' union all 
select 'B'

查询:

with cte as
(
select attribute1, max(rn) rn
from (
select attribute1, ROW_NUMBER() over (partition by attribute1 order by attribute1) rn
from @table ) x
group by attribute1
) select c.attribute1, case when c.rn>1 then 1 else 0 end Attribute_new
from @table t inner join cte c on  t.attribute1 = c.attribute1

答案 3 :(得分:0)

如果您对订单不感兴趣,可以使用以下内容:

CREATE TABLE T(val varchar(10));
INSERT INTO T VALUES 
('A'),
('B'),
('C'),
('A'),
('B'),
('F'),
('A'),
('B');


select  *, case when (count(val) over(partition by val)-1) = 0 then 0 else 1 end OneOrZero
from    T