3

我正在尝试进行查询,但找不到方法。

所以我有3张桌子

Table Card (card_id)

Table Level(leve_id, leve_desc)

Table CardDetails(cade_id, card_id, leve_id)

所以问题来了:每张卡片都有一个详细信息列表。

我想要一个查询来计算每张卡的数量,即具有完全相同详细信息的卡的数量,不包括卡本身。这意味着相同的列表leve_id

是否可以在普通的 t-sql 中实现它?

我希望我已经足够清楚,如果没有,我会尝试更好地解释我需要什么。

编辑:

目前我真的不需要知道它是哪张卡,但如果知道的话,它肯定会获得奖励积分。

编辑#2:让我们说表卡(card_id)1,2,3,4,5,6

Table level (leve_id, leve_desc)
(1, Level 1), (2,Level 2), (3,Level 3), (4,Level 4), (5, Level5), (6, Level6)

Table CardDetails (card_id, leve_id)
(1, 1), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1)
(3, 3), (3, 4), (4, 5), (5, 1), (5, 2), (5, 3)
(5, 4), (5, 5), (5, 6), (6, 1), (6, 3), (6, 4)

所以,结果应该是:

Card_id   Nbr_Cards
1    ..   2
2    ..   0
3    ..   2
4    ..   0
5    ..   0
6    ..   2
4

2 回答 2

4

如果我理解正确,你想要这样的东西

SELECT * 
FROM   cards c 
       INNER JOIN carddetails cd 
         ON c.card_id = cd.card_id 
       INNER JOIN (SELECT cade_id, 
                          leve_id 
                   FROM   carddetails 
                   GROUP  BY cade_id, 
                             leve_id 
                   HAVING COUNT (card_id) > 1)dups 
         ON cd.cade_id = dups.cade_id 
            AND cd.leve_id = dups.leve_id 

或者如果你喜欢 COUNT OVER

with dups as  (
SELECT 
   COUNT(CARD_ID)  OVER (PARTITION BY cade_id, leve_id) cardCount
   cade_id,
   leve_id
FROM  carddetails 
)
    SELECT * 
    FROM   cards c 
           INNER JOIN carddetails cd 
             ON c.card_id = cd.card_id 
           INNER JOIN  dups 
             ON cd.cade_id = dups.cade_id 
                AND cd.leve_id = dups.leve_id 
    WHERE cardCount > 1
于 2012-04-04T21:27:59.933 回答
4

如果我理解你的问题。
对于每张卡片,计算完全相等的详细信息的数量:

declare @CardDetails table (card_id int, leve_id int)

insert into @CardDetails values
(1, 1),         (1, 3), (1, 4), 
(2, 1), (2, 2), 
(3, 1),         (3, 3), (3, 4), 
(4, 5), 
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), 
(6, 1),         (6, 3), (6, 4)


select card_id,
       count(*) over(partition by leve_ids) - 1 as EqualCount
from 
  (
    select card_id,
           (select ','+cast(leve_id as varchar(10))
            from @CardDetails as C2
            where C1.card_id = C2.card_id
            order by C2.leve_id
            for xml path('')) as leve_ids
    from @CardDetails as C1
    group by card_id
  ) T
order by card_id

结果:

card_id     EqualCount
----------- -----------
1           2
2           0
3           2
4           0
5           0
6           2
于 2012-04-04T21:34:32.257 回答