1

我有一个myview以下列方式检索信息的视图:

ID  | ATTRNAME | ATTRVAL
1   | attr1    | a
2   | attr2    | b
3   | attr3    | c
4   | attr3    | d
..  | ..       | ..
..  | ..       | ..

我需要如下输出:

ATTRNAME | ATTRVAL
attr1    | a
attr2    | b
attr3    | Multiple Values

其中,如果一个属性 (ATTRNAME) 有一个值,则应该显示它,如果一个属性有多个值(例如 attr3),则应该显示文本“Multiple Values”。

我努力了:

SELECT DISTINCT attrname
       , CASE cnt
            WHEN 1 THEN TO_CHAR(attrval)
            ELSE 'Multiple Values'
         END AS attrval_rev
FROM   myview
JOIN   (SELECT   attrname, COUNT(attrval) AS cnt
        FROM     myview
        GROUP BY attrname) USING (attrname)

这可行,但这不是正确的解决方案,因为执行大约 11,000 行需要 8 多分钟。请帮忙!

4

3 回答 3

3

有一种更简单的方法:

SELECT ATTRNAME,
       CASE WHEN COUNT(*) = 1 THEN MIN(attrval) ELSE 'Multiple Values' END
 FROM myview
GROUP BY ATTRNAME

如果您仍然遇到性能问题,请告诉我。

于 2013-04-26T14:24:30.020 回答
2

尝试这个:

select attrname,
       (case when min(attrval) = max(attrval) then min(attrval)
             when min(attrval) is null then null
             else 'Multiple Values'
        end)
from myview
group by attrname

请注意,这NULL将作为有效值忽略。

您也可以将第一个列表设为when count(distinct attrval) = 1,但count(distinct)min()and贵一点max()

于 2013-04-26T14:20:38.177 回答
0

SELECT attrname, WHEN count(*) > 1 THEN 'Multiple Values' ELSE TO_CHAR(attrval) END FROM myview GROUP BY attrname

于 2013-04-26T14:21:18.620 回答