如何计算每行的数据量

时间:2014-02-17 05:17:28

标签: sql sql-server-2008

我有这张桌子:

   ID       Name    01  02  03  04  05  06  07

0000068 Name1                       V   VX  

0000069 Name2       V   VX  VX      V       V

0000070 Name3           V   V   V   V   V   V

这是一个缺席检查表,我想计算从01到07列的每一行的数据量,所以我希望第一行将得到2,第二行5和第三行6的结果。如果可能,我希望将结果添加为新列。有办法以某种方式工作吗?

4 个答案:

答案 0 :(得分:1)

如果它总是VVX,您可以将VX替换为V,连接 他们在一起并采取LEN()

SELECT *, LEN(REPLACE([01]+[02]+[03]+[04]+[05]+[06]+[07],'X','')) AS New_Ct
FROM YourTable

如果空白实际上是NULL,则必须将它们包裹在ISNULL()中:

SELECT *, LEN(REPLACE(ISNULL([01],'')+ISNULL([02],'')+ISNULL([03],'')+ISNULL([04],'')+ISNULL([05],'')+ISNULL([06],'')+ISNULL([07],''),'X','')) AS New_Ct
FROM Table1

演示:SQL Fiddle

答案 1 :(得分:0)

SELECT 01 + 02 + 03 + 04 + 05 + 06 + 07 AS total_number FROM table_name;

答案 2 :(得分:0)

尝试这样

SELECT  ID,Name,
(Case When[01] IS Null or [01] = '' then 0 else 1 end) +
(Case When[02] IS Null or [02] = '' then 0 else 1 end) +
(Case When[03] IS Null or [03] = '' then 0 else 1 end) +
(Case When[04] IS Null or [04] = '' then 0 else 1 end) +
(Case When[05] IS Null or [05] = '' then 0 else 1 end) +
(Case When[06] IS Null or [06] = '' then 0 else 1 end) +
(Case When[07] IS Null or [07] = '' then 0 else 1 end) AS Total
FROM table1;

FIDDLE DEMO

答案 3 :(得分:0)

如果列数是静态的,则可以使用简单的CASE表达式。

SELECT *,
 CASE WHEN [01] = '' OR [01] IS NULL THEN 0 ELSE 1 END +
 CASE WHEN [02] = '' OR [02] IS NULL THEN 0 ELSE 1 END +
 CASE WHEN [03] = '' OR [03] IS NULL THEN 0 ELSE 1 END +
 CASE WHEN [04] = '' OR [04] IS NULL THEN 0 ELSE 1 END +
 CASE WHEN [05] = '' OR [05] IS NULL THEN 0 ELSE 1 END +
 CASE WHEN [06] = '' OR [06] IS NULL THEN 0 ELSE 1 END +
 CASE WHEN [07] = '' OR [07] IS NULL THEN 0 ELSE 1 END [cnt]
FROM Table1;

An SQLfiddle to test with