在单个查询中从单个 SQL Server 表进行条件 SELECT/JOIN?
即使在搜索之后,我仍然在努力寻找正确类型的条件选择语句。
我和用户有一张桌子。有些是所有者,有些只是客人,如下所示:
TABLE A
UserID | UserType | Directory | RegisteredToID | Name
1 | Guest | | 3 | Bob
2 | Guest | | 3 | Susan
3 | Owner | abc | (null) | Charles
4 | Guest | | 20 | Hugh
etc...
我正在尝试获取一条查询语句,该语句会生成 Bob、Susan 和 Charles 记录,并显示每个记录的目录名称,如下所示:
Name | Directory
Bob | abc
Susan | abc
Charles | abc
换句话说,Bob 和 Susan 是Charles 的客人,但 Charles 的记录包含我想要的目录名称。希望我的问题有意义吗?
编辑:我应该提到这个扭曲......我不知道目录名称,只知道一个用户ID(例如Bob的1),并且正在尝试检索正确的目录名称以与每个目录关联用户,无论他们是否是访客。只有所有者记录才填写目录名称。
I'm struggling with the right type of conditional select statement here, even after searching.
I have a table with users. Some are owners, some are just guests, like so:
TABLE A
UserID | UserType | Directory | RegisteredToID | Name
1 | Guest | | 3 | Bob
2 | Guest | | 3 | Susan
3 | Owner | abc | (null) | Charles
4 | Guest | | 20 | Hugh
etc...
I'm trying to get one query statement that results the Bob, Susan, and Charles records with the directory name showing for each, like so:
Name | Directory
Bob | abc
Susan | abc
Charles | abc
In other words, Bob and Susan are guests of Charles, but Charles' record contains the directory name I want. Hope my question makes sense?
EDIT: I should have mentioned this twist....I won't know the directory name, just a userID (e.g. 1 for Bob) and am trying to retrieve the correct directory name to associate for each user, whether they are a guest or not. Only owner records have a directory name filled in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将表本身加入并使用
CASE
来决定 选择哪个目录。我无法想象(目前无法访问 SQL Server):
You need to join the table on itself and decide with
CASE
which Directory to select.Out of my head (don't have access to a SQL Server at the moment):
针对以下数据的 CTE 工作解决方案:
Working solution with a CTE for data below:
我修改了 JNK 的答案,以便它可以与目录名称的任意组合一起使用,而不仅仅是特定于“abc”
I modified JNK's answer so that it would work with any combination of directory names, not just specific to 'abc'
只是一种不同的做法......正如评论中指出的那样,如果用户可以是所有者和客人,那么这不起作用,我只需要更好地理解数据来调整它。
这基本上是说让所有隶属于所有者的人(包括所有者)忽略隶属关系未定义目录的情况。但是,如果所有者在表中多次列出...我可能会遇到此查询的问题。
Just a different way of doing it... as pointed out in comments, this doesn't work if a user can be an owner and a guest I'd just need to understand the data better to tweek it though.
This basically says get all the people affiliated with the owner including the owner ignoring situations where the affiliation doesn't have a directory defined. However if the owner is listed more than once in the table... I would likely have problems with this query.