我的表包含一些列,其中两列可以包含相同的值。 我的要求是,如果其中一个列包含值超过6次或两者都可以组合具有大于6次,那么它将被输出。
REF NONREF
--------------
7112 6162
7112 6162
7112 6162
7112 6162
7112 6162
7112 6162
6162 6237
7112 6237
Output should be ::
-------------------
7112
6162
如上所述,
REF having '7172' (7 times)
NONREF having '6162' (6 times) + REF having '6162' (1 time) = (7 times)
我尝试了下面的查询,但我知道它不符合要求
Select REF, count(*) from RDF_LINK
GROUP BY REF
Having count(*) > 6
UNION
Select NON, count(*) from RDF_LINK
GROUP BY NONREF
Having count(*) > 6
请帮助
答案 0 :(得分:4)
首先将两列合并为一个列表:
SELECT Ref AS Value FROM RDF_Link
UNION ALL
SELECT Non FROM RDF_Link
用作分组的源表:
SELECT Value, COUNT(*)
FROM (SELECT Ref AS Value FROM RDF_Link
UNION ALL
SELECT Non FROM RDF_Link)
GROUP BY Value
HAVING COUNT(*) > 6
答案 1 :(得分:1)
这也可以帮助你..
DECLARE @TAB TABLE (REF INT, NONREF INT)
INSERT INTO @TAB
VALUES (7112,6162),(7112,6162),(7112,6162),
(7112,6162),(7112,6162),(7112,6162),
(6162,6237),(7112,6237)
--SELECT * FROM @TAB
SELECT REF,
COUNT(*) [COUNT]
FROM @TAB GROUP BY REF HAVING COUNT(*) > 6
UNION ALL
SELECT NR.NONREF,
NR.COUNT + R.COUNT [COUNT]
FROM (SELECT NONREF,COUNT(*) [COUNT] FROM @TAB GROUP BY NONREF) NR
JOIN (SELECT REF,COUNT(*) [COUNT] FROM @TAB GROUP BY REF) R ON NR.NONREF = R.REF
WHERE (NR.COUNT + R.COUNT) > 6
<强>结果。强>