SQL 查询:连接两个单独行中的两个字段
我有以下两个表:
USER
FID UID VALUE
4 3 John
3 3 Doe
4 4 Jack
3 4 Russel
应该相当清楚,FID 3 = 姓氏,FID 4 = 姓名。
DATEDATA
UID DATE
3 1234
4 4321
我想连接这两个表,这样我最终会得到这样的结果:
UID DATE NAME SURNAME
3 1234 John Doe
4 4321 Jack Russel
或者... 或者...
UID DATE FULLNAME
3 1234 John Doe
4 4321 Jack Russel
有 SQL 专家吗?
这就是我到目前为止所拥有的:
SELECT UID, DATE, VALUE
from DATEDATA as D
left join USER as U
on U.uid = D.uid where fid = 3 OR fid = 4
但这给了我这个:
UID DATE VALUE
3 1234 Doe
3 1234 John
4 4321 Russel
4 4321 Jack
有人吗?
I have the following two tables:
USER
FID UID VALUE
4 3 John
3 3 Doe
4 4 Jack
3 4 Russel
Should be fairly clear that FID 3 = Surname, and FID 4 = Name.
DATEDATA
UID DATE
3 1234
4 4321
I want to join these two tables, so that I end up with something like this:
UID DATE NAME SURNAME
3 1234 John Doe
4 4321 Jack Russel
or... alternatively...
UID DATE FULLNAME
3 1234 John Doe
4 4321 Jack Russel
Any SQL gurus out there?
This is what I have so far:
SELECT UID, DATE, VALUE
from DATEDATA as D
left join USER as U
on U.uid = D.uid where fid = 3 OR fid = 4
But that gives me this:
UID DATE VALUE
3 1234 Doe
3 1234 John
4 4321 Russel
4 4321 Jack
Anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尽管只要第一个或最后一个为 NULL,这可能会给您一个 NULL 名称。如果您可以接受用户在系统中只有一个名称或另一个名称的情况,那么在这种情况下您可能需要使用 ISNULL 使任一名称成为空字符串。
Though this could give you a NULL name whenever either first or last is NULL. You may want to use an ISNULL to make either name an empty string in that case if you can accept cases where the user would only have one name or the other in your system.
您可以使用类似以下内容。它假设您始终有名字。如果您总是有一些字段并且它不是名字,请将其设为第一个字段并重新调整连接。如果您无法保证价值,请告诉我们,我们将提供更困难的解决方案。
You can use something like the following. It assumes you always have a first name. If you always have some field and it's not first name, make that the first from and readjust the joins. If you're never guaranteed a value, then let us know and we'll work a harder solution.