SQL Group by和内部列之间相交

时间:2017-09-13 06:09:17

标签: mysql sql sql-server set database-performance

我有以下表格结构

Source| Category         |Tag1Value     | Tag2Value
1-q1  | Engagement Type  | Micro Audit  |Audit
1-q1  | Engagement Type  | Micro Audit  |Micro Audit
1-q1  | Industry         | Insurance    |Insurance

我想为每个类别确定所有Tag1Value都在Tag2Values中是不是有任何基于集合的方法通过分组和交叉结果请帮助。有一种迭代方法,但我正在寻找一种更具性能的解决方案,因为数据是数百万。

1 个答案:

答案 0 :(得分:1)

SELECT Category, Tag1Value
FROM table_name t1
WHERE EXISTS (SELECT 1 FROM table_name WHERE Tag2Value = t1.Tag1Value)
  

更新

试试这个:

SELECT res.Category, res.tag, COUNT(res.tag) 
FROM
    (SELECT DISTINCT Category, Tag1Value tag
    FROM table_name
    UNION ALL
    SELECT DISTINCT Category, Tag2Value tag
    FROM table_name) res
GROUP BY res.Category, res.tag
HAVING COUNT(res.tag)>1

它返回:

category          |    tag
-----------------------------------
Industry          |    Insurance
Engagement Type   |    Micro Audit