SQL在表中查找值的出现,与列无关

时间:2014-01-23 15:22:24

标签: sql oracle sqlplus

我最近在一次采访中被问到,无论栏目信息如何,我都会在桌子上得到苹果,香蕉和橘子的数量。面试官要求提供苹果和香蕉的发生数量,并跳过橙子..

我没有在没有列名之前做过查询,请帮助..

THX

2 个答案:

答案 0 :(得分:0)

this approach的积分归@GordonLinoff所有。假设表中有5列:

select col_value, count(*) cnt from
(select (case when cols.num = 1 then t.col_1
              when cols.num = 2 then t.col_2
              when cols.num = 3 then t.col_3
              when cols.num = 4 then t.col_4
              when cols.num = 5 then t.col_5
         end) as col_value
from table t cross join
(select level as num from dual connect by level <= 5) cols)
where col_value in ('Apple', 'Banana')
group by col_value
order by 1;

该表将被完全扫描但只有一次,因此它比所有列组合的UNION ALL更有效。您还可以使用数据字典和动态SQL中的列信息重写此查询,以便它适用于任何表和任意数量的列。

答案 1 :(得分:0)

以下是我处理问题的方法。注意我在数据库中使用了一个表,我不幸地支持它。这也需要一些修改,然后需要查询插入行的表。

declare @columnName nvarchar(128)
declare @command nvarchar(250)
--drop table interview_idiocy
create table interview_idiocy
(
    Column_name varchar(128),
    Fruit varchar(50)
)
declare interview_idiocy cursor for 
    select 
        column_name 
    from 
        information_schema.columns 
    where 
        table_name = 'People'
        AND data_type in ('varchar', 'char')

open interview_idiocy 
fetch next from interview_idiocy into @columnName
WHILE @@FETCH_STATUS = 0
Begin
    set @command = 'insert interview_idiocy select count(' + @columnName +'),' + @columnName + ' from people where ' + @columnName + ' = ''apple'' group by ' + @columnName
    exec sp_executesql @command
    print @command
    fetch next from interview_idiocy into @columnName
end
close interview_idiocy
deallocate interview_idiocy