[英]How can I return a list of row names and column names where the value is greater than 0 in SQL?
I've put together a reconciliation tool in SQL Server which identifies the number of record breaks by field (col 2 - col 4) between two identical (data types/structure) sources.我在 SQL 服务器中组装了一个协调工具,它可以识别两个相同(数据类型/结构)源之间的字段(第 2 列 - 第 4 列)的记录中断数。 The output returned is in the format below, grouped on col 1.返回的 output 采用以下格式,按列 1 分组。
Col1 Col2 Col3 Col4
X 0 0 1
Y 0 1 1
Z 1 0 1
I am trying to manipulate the output so that it provides a list of the Col 1 identifier and the name of any column names (col 2 - col 4) which have breaks (value > 0).我正在尝试操作 output 以便它提供 Col 1 标识符的列表和任何具有中断(值 > 0)的列名(col 2 - col 4)的名称。
The expected output based on the above data would look like this.基于上述数据的预期 output 将如下所示。
Col1 FieldBreak
X Col2
Y Col3
Y Col4
Z Col2
Z Col4
I'm newer to SQL (6 months of professional experience) and am stuck.我对 SQL (6 个月的专业经验)较新,并且被卡住了。 Any help would be much appreciated!任何帮助将非常感激!
In any database, you can use:在任何数据库中,您都可以使用:
select col1, 'col2' as col
from t
where col2 = 1
union all
select col1, 'col3' as col
from t
where col3 = 1
union all
select col1, 'col4' as col
from t
where col4 = 1;
There are probably more efficient methods, but those depend on the database.可能有更有效的方法,但这些方法取决于数据库。 And for a small table efficiency may not be a concern.而对于小桌子来说,效率可能不是问题。
In SQL Server, you would unpivot using apply
:在 SQL 服务器中,您将使用apply
取消透视:
select t.col1, v.*
from t cross apply
(values ('col2', t.col2), ('col3', t.col3) . . .
) v(col, val)
where v.val is not null;
If you have a lot of columns, you can construct the expression using a SQL statement (from INFORMATION_SCHEMA.COLUMNS
) and/or using a spreadsheet.如果您有很多列,您可以使用 SQL 语句(来自INFORMATION_SCHEMA.COLUMNS
)和/或使用电子表格来构造表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.