我怀疑你有150列的有效理由。不过这里是你怎么能指望那些不为0时使用数据透视值:
DECLARE @table TABLE(customer_id int, col1 int, col2 int,
col3 int, col4 int, col5 int);
INSERT INTO @table
VALUES(1, 1, 2, 3, 4, 5) ,(2, 0, 2, 0, 4, 5)
SELECT count(CASE WHEN columns <> 0 THEN 1 END), customer_id
FROM @table as p
UNPIVOT
(columns FOR Seq IN
([col1], [col2], [col3], [col4], [col5])) AS unpvt
GROUP BY customer_id
结果:
5 1
3 2
如果要动态地选择列:
CREATE TABLE
test_table(customer_id int, col1 int, col2 int,
col3 int, col4 int, col5 int);
INSERT INTO test_table
VALUES(1, 1, 2, 3, 4, 5) ,(2, 0, 2, 0, 4, 5) ;
DECLARE @columnnames varchar(max)
SELECT @columnnames = coalesce(@columnnames + ',['+ column_name + ']' , '['+ column_name + ']')
FROM INFORMATION_SCHEMA.Columns
WHERE
table_name = 'test_table' and
column_name like 'col[0-9]%' and
table_schema = 'dbo'
ORDER BY column_name
DECLARE @sql varchar(max) =
'SELECT count(CASE WHEN columns <> 0 THEN 1 END), customer_id
FROM test_table as p
UNPIVOT
(columns FOR Seq IN
('[email protected]+')) AS unpvt
GROUP BY customer_id'
EXEC (@sql)
的可能重复[将ar中的所有列值相加在SQL Server中](http:// stackoverflow。com/questions/22434651/sum-all-column-value-in-a-row-in-sql-server) – Tanner 2015-02-10 08:58:36
请不要在发布之后45分钟做出重大更改 – 2015-02-10 09:27:26
我刚刚发布了一个示例查询以显示我的意思。顺便说一句,谢谢你的抬头。 @ t-clausen.dk – Ariox66 2015-02-10 09:39:51