基于相同id加入行的更好方法

时间:2013-12-08 19:41:28

标签: sql-server-2008

我想解决的问题是知道组合将出现相同注册次数和限制值33和5的频率。

这些是我在SQL数据库表中的几行:

      id  limitid    registrationid 
---------------------------------------
     113       33              3712 
     114        5              3712 
     116       33              3713 
     117        5              3713 
    1428       33              3714 
    1434        5              3720

RegistrationId在此表中可以包含0,1或两个值。 我正在寻找regsitrationId有两个值的情况,并将相应的limitid(和registrationid)放在一个结果集中,如:

    limitid1    limitid2    registrationid
------------------------------------------
          33           5             3712

为了达到这个目的,我使用了这个sql代码:

DECLARE @t TABLE(
    id int NOT NULL,
    regid int NOT NULL,
    limitid int not null
);
insert into @t
SELECT    Id,  RegistrationId, limitid
FROM      my-table
WHERE     (LimitId = 33) 
ORDER BY RegistrationId

DECLARE @t2 TABLE(
    id int NOT NULL,
    regid int NOT NULL,
    limitid int not null
);
insert into @t2
SELECT    Id,  RegistrationId, limitid
FROM      my-table
WHERE     (LimitId = 5) 
ORDER BY RegistrationId

declare @t3 Table(
    regid int NOT NULL,
    limitid1 int not null,
    limitid2 int not null
);
insert into @t3
SELECT     t1.RegId, t1.limitid, t2.limitid
FROM       @t as t1
join @t2 as t2
on t1.regid = t2.regid

select * from @t3

我的问题:是否有不同的/更好的方法来获得相同的结果?

谢谢!

1 个答案:

答案 0 :(得分:0)

我不是100%确定我完全理解你,但你可以通过以下方式实现输出:

SELECT t1.limitId AS limitid1,t2.limitId AS limitid2, t1.registrationID
FROM myTable t1
INNER JOIN myTable t2 ON t1.registrationID = t2.registrationID
WHERE t1.limitID = 33 
  AND t2.limitID = 5;

sqlfiddle demo

这为您提供了limitID1和limitID2的组合以及它们之间共享的registrationID。

编辑:

如果您不想获得每个registrationID,则只能获得MIN(t1.registrationID):

SELECT t1.limitId AS limitid1,
       t2.limitId AS limitid2, 
       MIN(t1.registrationID) AS Num_Records
FROM myTable t1
INNER JOIN myTable t2 ON t1.registrationID = t2.registrationID
WHERE t1.limitID = 33 AND t2.limitID = 5
GROUP BY t1.limitId,t2.limitId

sqlfiddle demo