使用自联接来检索唯一列

时间:2015-04-08 17:40:06

标签: sql

任何人都可以帮助我解决以下问题。

表1:

  MSISDN(PK) product_name  BASE_SOCBoo  PLAN_NAME   Limit

1   152     WHOADJTH2          N           ABC         10
2   152     WADADJTH5          N           ABC         20
2   152     THRWS33            Y           ABC        100
3   149     WADADJTH4          N           ABC          5
4   149     WADADJTH5          N           ABC          6

我正在尝试为msisdn显示必须有product_name,这是必需的(whoadjth2,whoadjth5,whoadjth4)和product_names THRWS31,THRWS32,THRWS33是可选的,当这些存在时base_soc_boo标志显示为已启用,否则&#39 ; N'

当我尝试下面的sql时,我得到了非常接近的输出

SELECT flex.msisdn,
  flex.product_name Flex_Soc,
  CASE
    WHEN base.product_name IN ('THRWS33', 'THRWS32', 'THRWS31')
    AND base.base_soc_boo   = 'Y'
    THEN base.product_name
    WHEN flex.product_name NOT IN ('THRWS33', 'THRWS32', 'THRWS31')
    AND flex.base_soc_boo       = 'N'
    THEN 'Not Prov'
  END base_soc,
  flex.plan_name,
  flex.limit
FROM table1,
  (SELECT b.product_name,
    b.plan_name,
    b.msisdn,
    b.base_soc_boo
  FROM table1 b
  WHERE product_name IN ('THRWS33', 'THRWS32', 'THRWS31')
  AND b.base_soc_boo IN ('Y')
  )base
WHERE flex.product_name <> base.product_name
AND flex.plan_name       = base.plan_name
AND flex.base_soc_boo   IN ('N','Y')

输出是:

    MSISDN  FLEX_SOC    BASE_SOC PLAN_NAME Limit   

1   152    WHOADJTH2    THRWS33      ABC     10
2   152    WADADJTH5    THRWS33      ABC     20
3   149    WADADJTH4    THRWS31      ABC      5
4   149    WADADJTH5    THRWS31      ABC      6

对于149,其中base_soc_boo标志是&#39; N&#39;需要显示为&#39; Not Provisioned&#39;

1 个答案:

答案 0 :(得分:1)

您的查询似乎过于复杂。在大多数数据库中,您可以使用窗口函数:

SELECT msisdn, flex_soc,
       coalesce(base_soc, 'Not Prov') as base_soc, plan_name, limit
from (SELECT flex.msisdn, flex.product_name as Flex_Soc,
             MAX(case when base_soc_boo = 'Y' then flex.product_name end) over
                 (partition by flex.msisdn) as base_soc,
            flex.plan_name, flex.limit
      FROM table1 flex
     ) flex
where base_soc_boo = 'N';

您没有指定数据库,因此ANSI兼容的语法似乎是合理的。

+----+--------+-----------+----------+-----------+-------+
|    | MSISDN | FLEX_SOC  | BASE_SOC | PLAN_NAME | Limit |
+----+--------+-----------+----------+-----------+-------+
|  6 |    152 | THRWS33   | THRWS33  | ABC       | 10240 |
|  7 |    152 | WADADJTH5 | THRWS33  | ABC       |  4092 |
|  8 |    152 | WHOADJTH2 | THRWS33  | ABC       |  1024 |
|  9 |    149 | WADADJTH4 | Not Prov | ABC       |   512 |
| 10 |    149 | WADADJTH5 | Not Prov | ABC       |  1024 |
+----+--------+-----------+----------+-----------+-------+