[英]SQL join using alias using calculated column
Here's a query which unpivots the individual year columns into 2 columns, yr and yr_val.这是一个查询,它将各个年份列反透视为 yr 和 yr_val 2 列。 When the yr=year(getdate()) the current year value will be returned.当 yr=year(getdate()) 时,将返回当前年份值。 GMB's query with the unpivot. GMB 使用 unpivot 查询。
select a.*
from d1 a
cross apply
(values (2018, a.[2018]),
(2019, a.[2019]),
(2020, a.[2020]),
(2021, a.[2021]),
(2022, a.[2022]),
(2023, a.[2023]),
(2024, a.[2024])) v(yr, yr_val)
where v.yr=year(getdate());
In pure SQL, you can't have a query dynamically choosing which column it should return.在纯 SQL 中,您不能让查询动态选择它应该返回的列。 A query returns a fixed set of columns, and the database needs to know that at the time it parses the query, before executing it.查询返回一组固定的列,数据库需要在解析查询时知道,然后再执行。
You could work something out with dynamic SQL - but it seems like it just makes things unecessarily complicated.您可以使用动态 SQL 解决一些问题 - 但它似乎只会使事情变得不必要地复杂。
A far better option would be to change your data model, in order to store each value in a separate row rather than in columns:更好的选择是更改您的数据模型,以便将每个值存储在单独的行而不是列中:
name year value
A 2018 18
A 2019 24
A 2020 72
B 2018 38
B 2019 19
B 2020 76
Then, the query is as easy as:然后,查询很简单:
select * from mytable where year = year(getdate())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.