如何避免以下情况得到唯一值
INPUT
id bike car bus htv
ss Y N N Y
ss N N N Y
KK Y N N Y
KK N N N Y
OUTPUT (expected)
id bike car bus htv
ss Y N N Y
KK Y N N Y
你可以分享查询以获得帮助吗?
答案 0 :(得分:1)
我认为您可以汇总并获取每列的最大值:
SELECT
id, MAX(bike) AS bike, MAX(car) AS car, MAX(bus) AS bus, MAD(htv) AS htv
FROM yourTable
GROUP BY id
这应该起作用的原因是Y
(对于是)在字典上大于N
(对于否)。因此,如果对于给定的id
,甚至有一个是值,则上述查询将报告是。只有在给定列没有任何地方的情况下才会报告否。
答案 1 :(得分:0)
以下几种方法取决于您希望如何选择保留值:
Oracle 11g R2架构设置:
CREATE TABLE table_name ( id, bike, car, bus, htv ) AS
SELECT 'ss', 'Y', 'N', 'N', 'Y' FROM DUAL UNION ALL
SELECT 'ss', 'N', 'N', 'N', 'Y' FROM DUAL UNION ALL
SELECT 'KK', 'Y', 'N', 'N', 'Y' FROM DUAL UNION ALL
SELECT 'KK', 'N', 'N', 'N', 'Y' FROM DUAL;
查询1 :获取每个ID组的每列的最大值:
SELECT id,
MAX( bike ) AS bike,
MAX( car ) AS car,
MAX( bus ) AS bus,
MAX( htv ) AS htv
FROM table_name
GROUP BY id
<强> Results 强>:
| ID | BIKE | CAR | BUS | HTV |
|----|------|-----|-----|-----|
| ss | Y | N | N | Y |
| KK | Y | N | N | Y |
查询2 :获取每个ID组中找到的第一行:
SELECT id, bike, car, bus, htv
FROM (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY id ORDER BY ROWNUM ) AS rn
FROM table_name t
)
WHERE rn = 1
<强> Results 强>:
| ID | BIKE | CAR | BUS | HTV |
|----|------|-----|-----|-----|
| KK | Y | N | N | Y |
| ss | Y | N | N | Y |
查询3 :获取最高bike
,然后最高car
,然后是最高bus
,然后是最高htv
的行{ {1}}:
id
<强> Results 强>:
SELECT id, bike, car, bus, htv
FROM (
SELECT t.*,
ROW_NUMBER() OVER (
PARTITION BY id
ORDER BY bike DESC, car DESC, bus DESC, htv DESC
) AS rn
FROM table_name t
)
WHERE rn = 1
查询4 :获取每个| ID | BIKE | CAR | BUS | HTV |
|----|------|-----|-----|-----|
| KK | Y | N | N | Y |
| ss | Y | N | N | Y |
组中Y
列的最大行数:
id
<强> Results 强>:
SELECT id, bike, car, bus, htv
FROM (
SELECT t.*,
ROW_NUMBER() OVER (
PARTITION BY id
ORDER BY
DECODE( bike, 'Y', 1, 0 )
+ DECODE( car, 'Y', 1, 0 )
+ DECODE( bus, 'Y', 1, 0 )
+ DECODE( htv, 'Y', 1, 0 ) DESC,
ROWNUM
) AS rn
FROM table_name t
)
WHERE rn = 1