第1题:十里挑一
Alan Flancman 在将一些遗留系统数据迁移到SQL数据库时遇到一个问题。表是这样的:
CREATE TABLE MyTable
(keycol INTEGER NOT NULL, f1 INTEGER NOT NULL, f2 INTEGER NOT NULL, f3 INTEGER NOT NULL, f4 INTEGER NOT NULL, f5 INTEGER NOT NULL, f6 INTEGER NOT NULL, f7 INTEGER NOT NULL, f8 INTEGER NOT NULL, f9 INTEGER NOT NULL, f10 INTEGER NOT NULL);
列f1到f10试图将一个数组放入表中。他需要一种优雅的方式来测试f1到f10列,找出列中只
包含一个非零值的行。你能找到多少种方法?请写出你认为最棒的一种方法。
T-SQL
很多
select * from MyTable
where case when nullif(f1,0) is null then 1 else 0 end +
case when nullif(f2,0) is null then 1 else 0 end +
case when nullif(f3,0) is null then 1 else 0 end +
case when nullif(f4,0) is null then 1 else 0 end +
case when nullif(f5,0) is null then 1 else 0 end +
case when nullif(f6,0) is null then 1 else 0 end +
case when nullif(f7,0) is null then 1 else 0 end +
case when nullif(f8,0) is null then 1 else 0 end +
case when nullif(f9,0) is null then 1 else 0 end +
case when nullif(f10,0) is null then 1 else 0