在sql中获取一对多关系的计数

时间:2013-03-26 07:52:31

标签: sql sql-server sql-server-2008

这是相关问题Related question的链接,

现在我有一个查询,它给出了我想要的公司名称

QUERY

 SELECT  CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN a.Name +'(Important) '
     WHEN IsHighPriority = 1 THEN a.Name +'(High Priority) '
    ELSE a.Name +''
END  AS CompanyName
 FROM    Company a
LEFT JOIN
(
    SELECT  Name, COUNT(*) totalCoupons
    FROM    Company
    GROUP   BY Name
) b ON a.name = b.name

现在我想要在(important)的情景中,我们正在测试如果公司有超过3张优惠券,那么在公司名称前面添加(Important)但我想这样做,如果 一家公司有超过3张优惠券

RejectProcessed = 0 and ReviewVerify = 0 and isPublish = 0 and ForSupervisor = 0 

然后我想添加该特定公司名称的重要面前。所以我该怎么做 。

如果您需要任何细节,请随时询问。

提前致谢

3 个答案:

答案 0 :(得分:1)

此查询解决了我的问题

SELECT  CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN company.Name +' (Important) '
        WHEN IsHighPriority = 1 THEN company.Name +' (High Priority) '
        ELSE company.Name +''
    END  AS CompanyName , company.id as Companyid
FROM    Company company
    left JOIN
    (
        SELECT  co.Name as coName, co.id as coid, COUNT(c.id) totalCoupons
        FROM    Company co, Coupon c
        where c.CompanyId = co.id   and c.RejectedProcessed = 1 and c.ReviewVerify = 0 and c.isPublish = 0 and c.ForSupervisor = 0 
        GROUP   BY co.Name, co.id
    ) b ON company.id = b.coid

答案 1 :(得分:0)

@ user2193861,是与公司表左边连接中的优惠券..?

LEFT JOIN
(
    SELECT  Name, COUNT(*) totalCoupons
    FROM    Coupon 
    GROUP   BY Name
) b ON a.name = b.name

答案 2 :(得分:0)

使用此..

SELECT CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN a.Name +'(Important) '

WHEN IsHighPriority = 1 THEN a.Name +'(High Priority) '

ELSE a.Name +''

END AS CompanyName

FROM Company a

LEFT JOIN

(

SELECT  Name, COUNT(*) totalCoupons

FROM    Company C

WHERE

EXISTS(

         select 1 

         from coupon P

         where P.RejectProcessed = 0 and P.ReviewVerify = 0

         and P.isPublish = 0 and P.ForSupervisor = 0 

         and P.CompanyName = C.Name

       )

and in second query..

use WHERE P.RejectProcessed = 0 and P.ReviewVerify = 0

and P.isPublish = 0 and P.ForSupervisor = 0
相关问题