SQL-如何循环比较数据列并在新列中输出结果?

huangapple go评论47阅读模式
英文:

SQL- How to do a loop to compare column of data and spit out a result in a new column?

问题

I want to possibly use a loop in SQL??, to go through a column of dates. If the dates are the same row by row, I want to output "Same" else if the dates are different, i want it to out put "Different" in a new column. If all the records are the same, I want it to display SAME in the new column. If one date is different from the whole list of Dates, all should display Different. All based on each ID.

This is what I want to accomplish

[Like this][1]

select distinct id, title, date, 
case when (max(date)) = date then 'Same' else 'Different' end as new_column
from table
where id in ('21','22')
group by 1,2,3

英文:

I want to possibly use a loop in SQL??, to go through a column of dates. If the dates are the same row by row, I want to output "Same" else if the dates are different, i want it to out put "Different" in a new column. If all the records are the same, I want it to display SAME in the new column. If one date is different from the whole list of Dates, all should display Different. All based on each ID.

This is what I want to accomplish

[Like this][1]

select distinct id, title, date, 
case when (max(date)) = date then 'Same' else 'Different' end as new_column
from table
where id in ('21','22')
group by 1,2,3

答案1

得分: 0

你不需要在这里聚合任何东西,也不需要选择不同的行,也许exists相关性是你想要的:

select Id, title, Date,
  case when exists (
    select * from table t2 where t2.Id = t.Id and t2.Date != t.Date
  ) then 'Different' else 'Same' end as "New column"
from table t
where id in (21, 22);
英文:

You don't need to aggregate anything here, nor select distinct rows perhaps an exists correlation is what you are after:

select Id, title, Date,
  case when exists (
    select * from table t2 where t2.Id = t.Id and t2.Date != t.Date
  ) then 'Different' else 'Same' end as "New column"
from table t
where id in (21, 22);

huangapple
  • 本文由 发表于 2023年2月24日 02:36:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定