在select语句中使用created column两次

时间:2014-06-03 14:28:01

标签: sql select

我在SQL中遇到这个查询的一个大问题。

select distinct 
    b.*, 
    case 
       when b.Cash > b2.Cash 
         then ((b.Cash - b2.Cash) / b.Cash) * 100 
    end as Increased, 
    ('Cash Increased by' + convert(VARCHAR(20), Increased))) as 
    Case
from 
    Accounting b
join 
   (…

在select语句中,我创建了列Increased。然后,我想创建另一个列Case,其值为Cash Increased by… (value from Increased column)

我的问题是如何在一个选择语句中完成?

1 个答案:

答案 0 :(得分:0)

您有两个选择

  • 将此查询用作子查询,并在外部查询
  • 中进行连接
  • 您必须将CASE..WHEN复制粘贴到连接

<强>子查询

SELECT
    *
    , ('Cash Increased by' + convert(VARCHAR(20), Increased))) AS CASE
FROM (
    SELECT DISTINCT
        b.*
        , CASE 
            WHEN b.Cash > b2.Cash THEN ((b.Cash - b2.Cash) / b.Cash) * 100
        END AS Increased
    FROM
        Accounting b JOIN (...)
) SubQuery

复制CASE部分

SELECT DISTINCT
    b.*
    , CASE 
        WHEN b.Cash > b2.Cash THEN ((b.Cash - b2.Cash) / b.Cash) * 100
    END AS Increased
    , (
        'Cash Increased by' + CONVERT(VARCHAR(20),
            CASE 
                WHEN b.Cash > b2.Cash THEN ((b.Cash - b2.Cash) / b.Cash) * 100
            END)
    ) AS CASE
FROM
    Accounting b JOIN (...)

注意 不要忘记转义(或更改)串联的别名。 CASE是大多数DMBS中的保留字!

注意2 下次请提及您正在使用的DBMS!