如何计算单行中的值?

时间:2011-12-09 14:12:05

标签: sql sql-server-2008 tsql

我有一张这样的表:

    | ID | X1 | X2 | X3 | .. | Xn |
    +----+----+----+----+----+----+
    | 1  | x  | '' | x  | '' | '' |
    +----+----+----+----+----+----+
    | 2  | '' | '' | x  | '' | '' |
    +----+----+----+----+----+----+
    | 3  | x  | x  | x  | '' | x  |
    +----+----+----+----+----+----+
'' = Empty string, not null

现在我想知道有多少' x'在第2行或第3行或n行。有没有一种简单的方法来实现这一目标?

使用MS SQL Server 2008

2 个答案:

答案 0 :(得分:3)

SELECT ID,
       (SELECT COUNT(*)
        FROM   (VALUES (X1),
                       (X2),
                       (X3),
                       /* ... */
                       (Xn)) T(X)
        WHERE  X = 'X') AS Num
FROM   YourTable  

答案 1 :(得分:1)

不要以这种方式存储数据。而是将其存储在XCoord,YCoord,Value的表中。然后你可以做类似的事情:

SELECT     XCoord, COUNT(Value) AS XTotal
FROM         TicTacTable
WHERE     (Value = 'x')
GROUP BY XCoord