英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论