使用内部联接sql查询计数

时间:2016-04-19 09:34:52

标签: sql-server sql-server-2008 tsql sql-server-2012

大家好我们有两张桌子“Subscriptioninfo,activationinfo” 这两个表格的结构是这样的

Subscriptioninfo表

   cert_id (int, PK)
   customer_email(string)
   subscription_key(string)
   activated_on (datetime)

activationinfo表:

    cert_id (int)
    activationcode(string)
    subscription_key(string , FK)
    activated_ts(datetime)

如果使用相同的年份和客户电子邮件ID输入 Subscriptioninfo ,则以下查询会将计数设为“ 1

SELECT COUNT(*) FROM Subscriptioninfo WITH (NOLOCK)
WHERE year(activated_On) = year(getdate()) AND customer_email =@CustomerEmail

我们有一个sp将数据插入两个表(即)一个条目到Subscriptioninfo,其中四个条目到activationinfo

如果subscriinfo的一个条目和activationinfo的两个条目

,我需要将count返回为“0”

如果有一个订阅条目的条目和四个条目激活信息,我需要将计数返回为“1”。

任何人都可以帮助解决这个问题如何通过join子句获得计数。

非常感谢...

尝试使用此查询,但它提供了activationinfo条目计数(即) 4 而不是 1

 SELECT COUNT(*) FROM subscriptioninfo csi join activationinfo aci on csi.subscription_key = aci.subscription_key
 WHERE year(Activated_On)  = year(getdate()) AND customer_email = 'xxx@cc.com' group by csi.subscription_key

2 个答案:

答案 0 :(得分:3)

使用let label = tapRecognizer.view as! UILabel 语句

CASE

答案 1 :(得分:1)

我只是尝试与众不同,表现可能更好,

;WITH CTE
AS (
    SELECT *
        ,row_number() OVER (
            ORDER BY cert_id
            ) rn
    FROM @activationinfo A
    )
SELECT *
    ,1 AS CountResult
FROM @Subscriptioninfo S
WHERE EXISTS (
        SELECT cert_id
        FROM CTE A
        WHERE s.cert_id = a.cert_id
            AND rn = 4
        )

UNION ALL

SELECT *
    ,0 AS CountResult
FROM @Subscriptioninfo S
WHERE EXISTS (
        SELECT cert_id
        FROM CTE A
        WHERE s.cert_id = a.cert_id
            AND rn < 4
        )