SQL根据记录中的其他字段创建字段

发布于 2024-12-26 23:15:55 字数 407 浏览 0 评论 0原文

我想根据另一个字段中的数据在 sql 查询中创建一个字段。例如:

First Name  Last Name  Hometown      State (created column based on Hometown)
Phil        Smith      Brooklyn      NY
Bill        Jones      Manhattan     NY
Abraham     Phillips   Cleveland     OH
Michael     Davis      Cincinnati    OH
William     Brett      Queens        NY

“State”列可以来自查找表或 if/else 语句中。我不知道如何做到这一点,所以我将不胜感激任何帮助。

I would like to create a field in my sql query based on the data in another field. For example:

First Name  Last Name  Hometown      State (created column based on Hometown)
Phil        Smith      Brooklyn      NY
Bill        Jones      Manhattan     NY
Abraham     Phillips   Cleveland     OH
Michael     Davis      Cincinnati    OH
William     Brett      Queens        NY

The "State" column could come from a look-up table or in an if / else statement. I'm not sure how to do this, so I would appreciate any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十秒萌定你 2025-01-02 23:15:55

这是一种“解决方案”,还有更多。

您可以创建一个名为“Person”的表,其中包含名字、姓氏和家乡(我想您可能已经拥有该表)以及一个名为“CityToState”的包含城市和州的查找表。

用适当的数据填充查找表(我确信它会很大)并发出查询,

select FirstName, LastName, Hometown, State 
    from Person left join CityToState on Hometown=City;

这应该会为您提供正确的数据,如果查找表中不存在该城市,则为该州返回 NULL。

基本上,它的作用是从 Person 获取所有数据并将其逐行连接到 CityToState 中的行,其中 HomeTown 与 City 相同。 “左”部分意味着即使 CityToState 中没有匹配的行,它也应该返回左表 (Person) 中的行。

This is one "solution", there are many more.

You could create one table called "Person" consisting of FirstName, LastName and Hometown (I presume you may have that table already) and a lookup table called "CityToState" with City and State.

Fill the lookup table with appropriate data (it'll be quite large, I'm sure) and issue the query

select FirstName, LastName, Hometown, State 
    from Person left join CityToState on Hometown=City;

That should give you the correct data, with NULL returned for the state if the city does not exist in the lookup table.

Basically what this does is to get all data from Person and join it, row by row with the row in CityToState where HomeTown is the same as City. The "left" part means that it should return the row from the left table (Person) even if there is no matching row in CityToState.

风铃鹿 2025-01-02 23:15:55

查找您正在使用的数据库的计算列(您没有在问题中说明)。以下是有关 SQL Server 的计算列的信息。

但是,我认为你应该使用不同的设计。如果是根据家乡查找州,一个外键就足够了,不需要重复数据。

look up computed column for the database you are using (which you do not state in the question). Here is info on SQL Server's Computed Columns.

However, I think you should use a different design. If you are looking up the state based on the hometown, a foreign key is enough, no need to duplicate the data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文