【问题标题】:count with inner join sql query用内连接 sql 查询计数
【发布时间】:2016-04-19 09:34:52
【问题描述】:

大家好,我们有两个表“订阅信息,激活信息” 两个表的结构是这样的

订阅信息表

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

激活信息表:

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

如果 Subscriptioninfo 条目具有相同年份和客户电子邮件 ID(这很好),则以下查询将计数为“one

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

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

如果订阅信息有一个条目,激活信息有两个条目,我需要将计数返回为“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

【问题讨论】:

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


    【解决方案1】:

    使用CASE 语句

    SELECT CASE WHEN COUNT(*) = 4 THEN 1
                WHEN COUNT(*) < 4 THEN 0
           END CountResults
    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
    

    【讨论】:

    • 如果 count() 小于 4 我需要返回 0 作为计数结果...只有当 count () = 4 时我才需要返回 1
    【解决方案2】:

    我只是想与众不同,可能性能更好,

    ;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
            )
    

    【讨论】:

    • 感谢您的解决方案.. 这将根据条件给出 1 或 0 的权利..
    猜你喜欢
    • 2014-03-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2016-03-29
    • 2015-06-21
    • 2013-07-06
    • 1970-01-01
    相关资源
    最近更新 更多