我很确定我遇到的问题是我不太清楚如何清楚地提出问题,所以我无法搜索答案。但是这里......
我的数据看起来像这样(在此简化):
ID | MailboxID | Connection | EmailID
0001 | M0001 | 1 | 9999
0002 | M0001 | 2 | 9999
0003 | M0002 | 1 | 9998
0004 | M0002 | 2 | 9998
0005 | M0002 | 2 | 9997
0006 | M0003 | 1 | 9996
ID是主键,因此它在表中是唯一的。 MailboxID表示邮件存储的邮箱.Connection告诉我邮箱中存在哪个内部连接(基本上是任务ID),EmailID是电子邮件的唯一标识符。
我需要返回MailboxID和EmailID相等但Connection不同的所有ID。在上面的示例中,我想要返回这些行:ID 0001-0002,0003-0004。谁能伸出援手?
答案 0 :(得分:3)
假设没有空值,你的数字是整数,你的字符串没有空格需要修剪:
CREATE TABLE [dbo].[Mailbox](
[ID] [int] NOT NULL,
[MailboxId] [varchar](10) NULL,
[Connection] [int] NULL,
[EmailId] [int] NULL,
CONSTRAINT [PK_Mailbox] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
INSERT INTO mailbox (ID, mailboxid, connection, emailid) Values (0001, 'M0001', 1, 9999);
INSERT INTO mailbox (ID, mailboxid, connection, emailid) Values (0002, 'M0001', 2, 9999);
INSERT INTO mailbox (ID, mailboxid, connection, emailid) Values (0003, 'M0002', 1, 9998);
INSERT INTO mailbox (ID, mailboxid, connection, emailid) Values (0004, 'M0002', 1, 9998);
INSERT INTO mailbox (ID, mailboxid, connection, emailid) Values (0005, 'M0002', 2, 9997);
INSERT INTO mailbox (ID, mailboxid, connection, emailid) Values (0006, 'M0003', 1, 9996);
select m1.Id, m2.id
from Mailbox m1, Mailbox m2
Where m1.id <> m2.id
AND M1.mailboxid = m2.mailboxid
and m1.emailid = m2.emailid
and m1.connection <> m2.connection
and m1.id < m2.id
应该给你这个:
Id id
1 2
如果需要,您可以修剪邮箱ID并添加空检查(如果这也是问题)。
答案 1 :(得分:2)
也许你想要这样的东西:
select a.ID, b.ID
from tableName a
join tableName b
on a.ID > b.ID
and a.MailboxID = b.MailboxID
and a.EmailID = b.EmailID
and a.Connection <> b.Connection
另一种方法是按邮箱ID和电子邮件ID进行分组,并显示每个特定组中涉及的所有ID和连接。