问题陈述:
简单示例:
输入表:
A | B | C x | y | z w | y | z u | y | z u | v | z v | v | z
标准:B和C列必须相同,两行才能成对。
输出:
x | y | z w | y | z u | v | z v | v | z
在纯SQL(或Oracle方言,如果特定功能有帮助)中解决问题有哪些提示?
答案 0 :(得分:2)
如果您可以使用窗口分析功能:
CREATE TABLE TT1 (A VARCHAR(4), B VARCHAR(4), C VARCHAR(4))
INSERT INTO TT1 VALUES ('x','y','z')
INSERT INTO TT1 VALUES ('w','y','z')
INSERT INTO TT1 VALUES ('u','y','z')
INSERT INTO TT1 VALUES ('u','v','z')
INSERT INTO TT1 VALUES ('v','v','z')
INSERT INTO TT1 VALUES ('k','w','z')
SELECT A.A, A.B, A.C
FROM
(SELECT *, ROW_NUMBER() OVER (PARTITION BY B,C ORDER BY A DESC) RN, COUNT(*) OVER (PARTITION BY B,C ) RC
FROM TT1) A
WHERE A.RN <=2 AND RC>1
输出:
A B C
---- ---- ----
v v z
u v z
x y z
w y z
答案 1 :(得分:1)
对要匹配的行匹配COUNT()
分析函数分区:
SELECT A, B, C
FROM (
SELECT t.*,
COUNT(*) OVER (
PARTITION BY B, C
ORDER BY A
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS current_rn,
COUNT(*) OVER (
PARTITION BY B, C
ORDER BY A
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING
) AS next_rn
FROM table_name t
)
WHERE MOD( current_rn, 2 ) = 0
OR MOD( next_rn, 2 ) = 0;
<强>输出强>:
A B C
- - -
u y z
w y z
u v z
v v z