如何在查询本身内更改sql查询的单个列的结果?

时间:2014-07-29 14:34:30

标签: sql sql-server database

我正在运行以下SQL查询:

SELECT
    share_name AS "Server", 
    Capacity, Available,
    ((available * 1.00) / capacity) * 100 as "% Free"
FROM 
    storage_info
WHERE 
    share_name LIKE '%192.168.1.1%'
    OR share_name LIKE '%192.168.1.2%'
    OR share_name LIKE '%192.168.1.3%'
    OR share_name LIKE '%192.168.1.4%';

返回' share_name'的结果列作为IP地址,因为它们存储在表中。

是否可以在查询中更改IP地址的输出内容 - 与“AS'”相同。更改列的名称?

4 个答案:

答案 0 :(得分:2)

您可以按照以下方式执行此操作:

SELECT
    CASE 
        WHEN 
            share_name = '192.168.1.1' 
        THEN 
            'Server 1' 
        ELSE 
            share_name 
    END AS "Server", 
    Capacity, Available,
    ((available * 1.00) / capacity) * 100 as "% Free"
FROM 
    storage_info
WHERE 
    share_name LIKE '%192.168.1.1%'
    OR share_name LIKE '%192.168.1.2%'
    OR share_name LIKE '%192.168.1.3%'
    OR share_name LIKE '%192.168.1.4%';

答案 1 :(得分:1)

;WITH map([IP],[NAME]) AS (
    select
        [IP],[NAME]
    from (values
        ('192.168.1.1','Server1'),
        ('192.168.1.2','Server2')
)
SELECT
    ISNULL(map.name,share_name) AS "Server", 
    Capacity, Available,
    ((available * 1.00) / capacity) * 100 as "% Free"
FROM 
    storage_info
LEFT JOIN map on
    storage_info.share_name = map.IP
WHERE 
    share_name LIKE '%192.168.1.1%'
    OR share_name LIKE '%192.168.1.2%'
    OR share_name LIKE '%192.168.1.3%'
    OR share_name LIKE '%192.168.1.4%';

答案 2 :(得分:1)

您可以使用它来获得所需的输出。只需为要以不同方式输出的每个IP添加一个案例。

SELECT
    CASE WHEN share_name LIKE '%192.168.1.1%' THEN 'Server 1' END AS "Server", 
    Capacity, Available,
    ((available * 1.00) / capacity) * 100 as "% Free"
FROM 
    storage_info
WHERE 
    share_name LIKE '%192.168.1.1%'
    OR share_name LIKE '%192.168.1.2%'
    OR share_name LIKE '%192.168.1.3%'
    OR share_name LIKE '%192.168.1.4%';

您可能不需要WHERE条件中的主要通配符,这会大大加快此查询速度。

答案 3 :(得分:1)

SELECT CASE WHEN share_name LIKE '%192.168.1.1%' THEN 'SERVER 1'
            WHEN share_name LIKE '%192.168.1.2%' THEN 'SERVER 2'
            WHEN share_name LIKE '%192.168.1.3%' THEN 'SERVER 3'
            WHEN share_name LIKE '%192.168.1.4%' THEN 'SERVER 4'
            ELSE share_name END AS "Server",
       Capacity, Available, ((available * 1.00) / capacity) * 100 as "% Free"
FROM storage_info
WHERE share_name LIKE '%192.168.1.1%'
   OR share_name LIKE '%192.168.1.2%'
   OR share_name LIKE '%192.168.1.3%'
   OR share_name LIKE '%192.168.1.4%';