根据交集表逻辑创建模板

时间:2011-10-27 19:27:26

标签: sql oracle intersection

我不确定如何描述这个问题,但我正在尝试就哪些代码归因于关税提出建议。我在Oracle中这样做。

这是我的数据库结构:

CODE (
    CODEID *PK NCHAR(10)
)

CODETARIFF (
    TARIFFNO NCHAR(15) *PK *FK
    CODEID NCHAR(10) *PK *FK
)

TARIFF (
    TARIFFNO NCHAR(15) *PK
)

所以我正在尝试逻辑地制作应该为关税分配哪些代码的模板。我想象的是:“6关税还有这两个与它们相关的代码”

我尝试了这个,但是为每个代码返回的计数并没有真正显示模板,它们只显示了当一个代码与我指定的两个代码一起出现时的发生率。

SELECT COUNT(*), CodeID
FROM CodeTariff
  INNER JOIN (
    SELECT TariffNo, COUNT(*) 
    FROM CodeTariff
    WHERE CodeID IN ('ABC', 'DEF') 
    GROUP BY TariffNo
    HAVING COUNT(*) > 1) SQ 
  ON CodeTariff.TariffNo = SQ.TariffNo 
WHERE CodeID NOT IN ('ABC', 'DEF')
GROUP BY CodeTariff.CodeID
ORDER BY COUNT(*) DESC;

很抱歉,如果这令人困惑。

我不知道这是否可行,但我正在寻找这样的输出:

数据:     TariffCode

TariffNo        CodeID

1111            ABC
1111            DEF
2222            ABC
2222            DEF
2222            GHI
2222            JKL
3333            ABC
3333            DEF
3333            GHI
3333            JKL

产出:(给予关税1111时)

CodesToAdd      Count

GHI, JKL        2

这样我就可以显示:

其他2种关税的代码GHI和JKL与它们相关联。您是否要将这些代码添加到关税1111?

2 个答案:

答案 0 :(得分:0)

尝试这些魔法:

SELECT     Code, COUNT(*) AS Count
FROM         (SELECT     dbo.TariffCode.Tariff, dbo.TariffCode.Code
                   FROM          dbo.TariffCode LEFT OUTER JOIN
                                              (SELECT     TariffCode_2.Tariff, TariffCode_2.Code
                                                FROM          dbo.TariffCode AS TariffCode_2 INNER JOIN
                                                                           (SELECT     Tariff, Code
                                                                             FROM          dbo.TariffCode AS TariffCode_1
                                                                             WHERE      (Tariff = '1111')) AS TariffsWithSharedCodes ON TariffCode_2.Code = TariffsWithSharedCodes.Code AND 
                                                                       TariffCode_2.Tariff <> '1111') AS MutualCodes ON dbo.TariffCode.Tariff = MutualCodes.Tariff AND 
                                          dbo.TariffCode.Code = MutualCodes.Code
                   WHERE      (MutualCodes.Code IS NULL) AND (dbo.TariffCode.Tariff <> '1111')) AS MissingCodes
GROUP BY Code
ORDER BY Count DESC, Code

这是T-SQL,对不起,但你会明白这个想法

答案 1 :(得分:0)

希望下面的脚本可以帮助你。它将获得所有可能的关税,不仅仅是'1111':

with temp as (
  select tariffno, tariffno2, codeid 
  from (
    select distinct c1.tariffno, c2.tariffno as tariffno2, c2.codeid
    from tariffcode c1
    join tariffcode c2 on c1.tariffno != c2.tariffno and c1.codeid != c2.codeid 
  ) c1 
  where 
    not exists (select 1 from tariffcode where tariffno = c1.tariffno and codeid = c1.codeid)
)
select tariffno, codeid, count(*) as cnt from temp group by tariffno, codeid;