是否可以替换SQL查询中的值?

时间:2011-08-02 08:39:15

标签: sql sql-server tsql

我想知道在SQL查询中是否有可能用其他东西替换某些值,或者如果我需要在后处理中这样做。

让我解释一下。我有这张桌子:

|username| accepted |
|--------|----------|
|  toto  |   NULL   |
|--------|----------|
|  foo   |    0     |
|--------|----------|
|  Rick  |    1     |
|--------|----------|
|  bar   |    1     |
|--------|----------|

我想知道accepted(可空位)每个值的行数。我正在运行此查询:

SELECT [accepted], count(*) FROM my_table GROUP BY [accepted]

应返回:

NULL   1  
false  1  
true   2

有没有办法用更有意义的标签替换accepted值?理想情况下,我希望有类似的东西:

not_available 1
not_accepted  1
accepted      2

SQL Server 2008 R2是否可行?

THX。

4 个答案:

答案 0 :(得分:11)

如果您有几个值:

SELECT CASE [accepted] 
WHEN 0 THEN 'not_accepted' 
WHEN 1 THEN 'accepted '
ELSE 'not_available' END AS accepted
, count(*) 
FROM my_table 
GROUP BY CASE [accepted] 
WHEN 0 THEN 'not_accepted' 
WHEN 1 THEN 'accepted '
ELSE 'not_available' END

答案 1 :(得分:3)

使用CASE

SELECT
    CASE [accepted]
       WHEN 1 THEN 'accepted'
       WHEN 0 THEN 'not_accepted'
       ELSE 'not_available' --NULL
    END AS [accepted], count(*)
FROM my_table
GROUP BY --try [accepted] by itself first
    CASE [accepted]
       WHEN 1 THEN 'accepted'
       WHEN 0 THEN 'not_accepted'
       ELSE 'not_available' --NULL
    END

您可能必须在GROUP BY中使用整个CASE。除非你这样做

SELECT
    CASE [accepted]
       WHEN 1 THEN 'accepted'
       WHEN 0 THEN 'not_accepted'
       ELSE 'not_available' --NULL
    END AS [accepted], CountOfAccepted
FROM
   (SELECT [accepted], count(*) AS CountOfAccepted
    FROM my_table GROUP BY [accepted]) foo

答案 2 :(得分:2)

SELECT
    CASE [accepted]
        WHEN 1 THEN 'accepted', 
        WHEN 0 THEN 'not accepted',
        ELSE 'not available'
    END AS [accepted],
    count(*) 
FROM my_table GROUP BY [accepted]

不确定这是否完全正确,并且现在没有可用于测试的SQL Server,但应该是这样的。

编辑:aww,已发布

答案 3 :(得分:1)

是的,它在那里......您可以修改您的查询,如下所示 -

SELECT decode(accepted,NULL,'not_available' ,1,'accepted',0,'not_accepted'),count(*) 
FROM my_table GROUP BY 
 decode(accepted,NULL,'not_available' ,1,'accepted',0,'not_accepted')

它应该根据需要提供输出..

可能是解码功能不存在,那么你可以在那里使用case ..

SELECT 
case accepted 
    WHEN 1 THEN 'accepted'
    WHEN 0 THEN 'not_accepted'
    ELSE 'not_available' 
end,count(*) 
    FROM my_table GROUP BY     
 case accepted 
    WHEN 1 THEN 'accepted'
    WHEN 0 THEN 'not_accepted' 
    ELSE 'not_available' end