【问题标题】:SQL Find occurrences of value in a table regardless of columnsSQL在表中查找值的出现而不考虑列
【发布时间】:2014-02-14 05:56:58
【问题描述】:

我最近在一次采访中被问到如何计算表格中的苹果、香蕉和橙子,而不考虑列信息。面试官要求提供苹果和香蕉的出现次数,跳过橘子。

我从来没有做过没有列名的查询,请帮忙..

谢谢

【问题讨论】:

  • 使用列索引,第一列1,....
  • 这是因为在设计良好的数据库模式中,您不会倾向于将数据随机分散在多个列中。如果两条数据具有相同的“类型”,因此您想要比较它们、将它们加在一起或其他任何方式,它们确实应该都出现在 same 列中。
  • 这可能很傻。我们可以将所有列连接成单列并做一个substr吗?

标签: sql oracle sqlplus


【解决方案1】:

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

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

【讨论】:

  • 我猜它是 T-SQL 而 OP 将问题标记为 oracle。也请使用代码格式化功能以获得更好的可读性。
【解决方案2】:

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 中的列信息重写此查询,使其适用于任何表和任何数量的列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多