IF(Count(*)> 1)

时间:2012-08-03 18:19:43

标签: sql tsql

我正在尝试查看两个表,TableA和TableB打印出任何显示超过1个计数的TableA.ID。 TableA看起来像这样:

ID  |  Code
------------
1   |  A
2   |  B
3   |  C

表B看起来像

ID  |  AID |   EffectiveDate  |  ExpirationDate
------------------------------------------------
1   |  1   |  2012-01-01      |  2012-12-31
2   |  1   |  2012-01-01      |  2012-12-31
3   |  2   |  2012-01-01      |  2012-12-31
4   |  3   |  2012-01-01      |  2012-12-31

我使用的查询如下所示:

DECLARE @MoreThanOne varchar(250)
SET @MoreThanOne = ''
IF((SELECT COUNT(*) FROM TableA
WHERE EXISTS(
SELECT TableB.ID
        ,TableB.EffectiveDate
        ,TableB.ExpirationDate
     FROM TableB
     WHERE TableB.AID = TableA.ID
        and GETDATE() Between TableB.EffectiveDate and TableB.ExpirationDate
) 
GROUP BY TableA.Code) > 1)
BEGIN
--SET @MoreThanOne = @MoreThanOne + TableA.Code + CHAR(10)

END


PRINT @MoreThanOne

我知道我的嵌套查询在重新编写时会起作用,它会在TableA中的唯一代码中打印所有的计数。 我知道我不能使用我注释掉的内容,因为我无法访问TableA.Code。 我的问题是有另一种方法可以做到这一点,或者我如何能够访问TableA.Code以获取Message MoreThanOne。

谢谢你的帮助!

4 个答案:

答案 0 :(得分:4)

此查询将为您提供表B中重复的所有AID的代码:

SELECT Code
FROM TableA
WHERE AID IN
(
    SELECT AID
    FROM TableB
    GROUP BY AID
    HAVING COUNT(*) > 1
)

您可能还希望将存储过程中的WHERE条件添加到内部选择中。

答案 1 :(得分:1)

试试这个

SELECT TableA.ID, TableA.Code, Count(*) As Cnt

         FROM TableB, TableA
         WHERE TableB.AID = TableA.ID
            and GETDATE() Between TableB.EffectiveDate and TableB.ExpirationDate
         GROUP BY TableA.ID, TableA.Code
         HAVING COUNT(*) > 1

答案 2 :(得分:0)

您可以非常简单地执行此操作,无需加入:

SELECT tableb.AID
FROM TableB
WHERE GETDATE() Between TableB.EffectiveDate and TableB.ExpirationDate
group by tableb.AID
having count(*) > 1

这只是通过AID聚合tableB,返回具有多个记录的值。如果你想要代码,你只需要加入TableA。

答案 3 :(得分:0)

这应该是你:

select Code      = a.Code ,
       Frequency = count(*)
from table_a a
join table_b b on b.aid = a.id
              and current_timestamp between b.EffectiveDate and b.ExpirationDate
group by a.Code
having count(*) > 1
order by 2 desc -- order in descending sequence by frequency
         1      -- then ascending sequence by code