比较sql中组内的列
我对 SQL 很陌生,所以如果这个问题很难理解,我深表歉意。
假设我有一个像这样的表:
Name Birthday Bob 7/18 Bob 7/18 Mark 5/10 Mark 7/5 Sue 2/1 Joe 1/14 Joe 1/14 Joe 1/2 Jeff 9/16 Jeff 3/20 Jeff 6/13 [...]
我想执行一个选择语句,为我提供具有多个不同生日的人的姓名。
因此,对于我的示例表,输出将是 Mark、Joe 和 Jeff。
感谢您的帮助。
I'm very new to SQL so I appologize if this question is difficult to understand.
Let's say I have a table like:
Name Birthday Bob 7/18 Bob 7/18 Mark 5/10 Mark 7/5 Sue 2/1 Joe 1/14 Joe 1/14 Joe 1/2 Jeff 9/16 Jeff 3/20 Jeff 6/13 [...]
I would like to perform a select statement that gives me the Names of the people who have more than one distinct Birthdays.
So, for my example table, the output would be Mark, Joe, and Jeff.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据我的理解,重新措辞您的问题陈述:
所有名称,其中:
- 该名称有多个与之关联的颜色
- 其中,至少有两种颜色具有与其关联的不同生日
我不确定的是,与同一名称关联的相同颜色是否可能有两个不同的生日?
如果
否
,则颜色变得无关紧要,您只需要一个具有超过 1 个不同生日的名称即可。If `yes`, you need to find another record with the same name, but also a different colour AND a different birthday.
SELECT
Name
FROM
yourTable
WHERE
EXISTS (SELECT * FROM yourTable as [lookup] WHERE Name = yourTable.Name AND Birthday yourTable.Birthday AND Colour yourTable.Colour)
GROUP BY
Name
A re-wording as I understand your problem statement:
All Names where:
- The name has more than one Colour associated to it
- Of those, at least two Colours have different birthday's associated to them
What I'm unsure of is whether it's possible to have two different birthdays for the same colour associated to the same name?
If
no
, the colour becomes irrelevant, you just want a name with more than 1 different birthday associated to it.If `yes`, you need to find another record with the same name, but also a different colour AND a different birthday.
SELECT
Name
FROM
yourTable
WHERE
EXISTS (SELECT * FROM yourTable as [lookup] WHERE Name = yourTable.Name AND Birthday yourTable.Birthday AND Colour yourTable.Colour)
GROUP BY
Name
试试这个:
SQL Server 的工作示例代码:
输出:
try this:
working sample code for SQL Server:
OUTPUT:
您可以通过几种不同的方式来完成此操作。您可以
JOIN
表自身,也可以使用EXISTS
子句。或者
您也可以使用
HAVING
子句解决这个特定问题:You can do this several different ways. You can either
JOIN
the table to itself, or you can use theEXISTS
clause.or
You could also solve this particular problem using the
HAVING
clause: