描述性列而不是值

时间:2017-09-26 20:32:55

标签: sql sql-server

select *
    , AreaLeftOver=(KmSquared) % (20761)
    , WhalesUnit = (KmSquared)/(20761)
    , WhalesComparison= case when((KmSquared)/(20761) * (KmSquared) % (20761)  )>0 then (KmSquared)/(20761) * (KmSquared) % (20761) else  'Smaller' end
from CountriesByArea 
order by Country

如何为WhalesComparison创建描述性列?

我尝试使用case when语句,但它给了我int值,这会将转换错误从' varchar转移到bigint'。

注意:我只有Country,KmSquared列,我从计算函数派生出来。

2 个答案:

答案 0 :(得分:1)

您不能在单个列中混合使用数据类型。您有一个返回int或字符串的公式。你不能这样做,但你可以将所有内容作为字符串返回。在计算中,您也不需要围绕每列的括号。

select *
    , AreaLeftOver= KmSquared % 20761
    , WhalesUnit = KmSquared / 20761
    , WhalesComparsion= case when KmSquared / 20761 * KmSquared % 20761 > 0 then convert(varchar(10), KmSquared / 20761 * KmSquared % 20761) else  'Smaller' end
from CountriesByArea 
order by Country

或者更好的方法是在应用程序中包含“Smaller”文本,然后只返回NULL。

select *
    , AreaLeftOver= KmSquared % 20761
    , WhalesUnit = KmSquared / 20761
    , WhalesComparsion= case when KmSquared / 20761 * KmSquared % 20761 > 0 then KmSquared / 20761 * KmSquared % 20761) end
from CountriesByArea 
order by Country

答案 1 :(得分:0)

SELECT POSITION
,COUNTRY
,KmSquared
,AreaLeftOver
,WhalesUnit
,CASE WHEN CALC <= 0 THEN 'SMALLER'
WHEN CALC > 0 THEN AreaLeftOver+''+ 'x WALES PLUS'+ '' + WhalesUnit
ELSE 'NONE'
END AS [Wales Comparision]
FROM
(
select POSITION
,COUNTRY
,KmSquared
,CAST(KmSquared % 20761 AS nvarchar(MAX)) AS AreaLeftOver
,CAST(KmSquared / 20761 AS nvarchar(MAX)) AS WhalesUnit
,((KmSquared % 20761) * (KmSquared / 20761)) AS CALC
from CountriesByArea 
)A
order by Country