SQL Counting成员显示某些代码值的次数

时间:2011-09-15 16:23:12

标签: sql

我正在运行一个查询,该查询返回成员的位置以及该成员注册的产品。每当成员向其产品提出索赔时,他们都会获得与其关联的收入代码。以下是我现在的查询:

SELECT DISTINCT
    e.State,
    f.Product,
    d.MemberID,
    b.RevenueCode
FROM
    Claims a
INNER JOIN
    dw.Revenue b
ON
    a.RevenueKey = b.RevenueKey
INNER JOIN 
    dw.Member d
ON
    a.MemberKey = d.MemberKey
INNER JOIN  
    dw.Product f
ON
    a.ProductKey = f.ProductKey
INNER JOIN
    dw.State
ON
    a.StateKey = f.StateKey
WHERE
    b.RevenueCode IN ('0134', '0135')

它返回如下所示的集合:

State         Product            MemberID              RevenueCode
MN            xxx                945-234-245           0134
MN            xxx                945-234-245           0135
SD            xxx                231-345-235           0134

当MemberID具有与之关联的0134和0135 RevenueCodes时,它们被视为属于特殊类别。如何修改我的上述查询以计算MemberID按州和按产品分类的RevenueCodes的次数?

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT
    e.State,
    f.Product,
    d.MemberID,
    b.RevenueCode.
    CASE WHEN EXISTS(
      SELECT NULL
      FROM Claims a1
      JOIN dw.Revenue b1 ON a1.RevenueKey = b1.RevenueKey
      JOIN dw.Member  d1 ON a1.MemberKey = d1.MemberKey
      JOIN dw.Product f1 ON a1.ProductKey = f1.ProductKey
      WHERE b1.RevenueCode IN('0134', '0135') AND 
        d1.MemberID = d.MemberID AND
        f1.ProductKey = f.ProductKey AND
        f1.StateKey = f.StateKey
    ) THEN 1 ELSE 0 END As IsSpecialCategory
FROM
   ...

答案 1 :(得分:1)

SELECT DISTINCT
    e.State
    ,f.Product
    ,d.MemberID
    ,b.RevenueCode
    ,(SELECT 1
    FROM Claims AS a1
    INNER JOIN dw.Revenue AS b1 ON a1.RevenueKey = b1.RevenueKey
    WHERE b1.RevenueCode IN ('0134', '0135')
        AND b.revenuekey = b1.revenuekey
        AND a.MemberKey = a1.Memberkey
    HAVING COUNT(DISTINCT b1.RevenueCode) = 2) AS SpecialCategory
FROM Claims a
INNER JOIN dw.Revenue b ON a.RevenueKey = b.RevenueKey
INNER JOIN dw.Member d ON a.MemberKey = d.MemberKey
INNER JOIN dw.Product f ON a.ProductKey = f.ProductKey
INNER JOIN dw.State ON a.StateKey = f.StateKey
WHERE b.RevenueCode IN ('0134', '0135')

答案 2 :(得分:0)

想出来......根据需要计算不同的收入代码和按州,产品和成员ID分组