2017-03-14 14 views
1

tavg intデータ型列のnull値に対して 'no data'を出力しようとしていますが、 "then sum((tmin + tmax)/ 2)"の部分になります。どんな助け?すべての戻り値の型が同じである必要があります場合はvarchar値 'string'をデータ型intに変換するときに変換を取得できません

select 
    Case 
    when (tavg > -59 and tmin is NULL and tmax is NULL) then tavg 
    when (tavg > -59 and tmin is NULL and tmax > -59) then tavg 
    when (tavg is null and tmin >-59 and tmax > -59) then sum((tmin+tmax)/2) 
    when (tavg is null and tmin is null and tmax is null) then 'No data' 
    else cast(tavg as varchar(50)) end as 'avg_temp', 
    case 
    when tmin is null then 'No data' else cast(tmin as varchar(50)) end as 'Minimum Temperature', 

答えて

4

そうSQLは最高の優先順位にすべての戻り値の型をキャストしようとします。 SQLは 'No Data'をint(より高い優先順位)に変換しようとしているので、あなたが得ているエラーです。あなたはすべてのケースからvarchar型を返す場合、それは動作するはずです:説明のため

select 
    Case 
    when (tavg > -59 and tmin is NULL and tmax is NULL) then cast(tavg as varchar(50)) 
    when (tavg > -59 and tmin is NULL and tmax > -59) then cast(tavg as varchar(50)) 
    when (tavg is null and tmin >-59 and tmax > -59) then cast(sum((tmin+tmax)/2) as varchar(50)) 
    when (tavg is null and tmin is null and tmax is null) then 'No data' 
    else cast(tavg as varchar(50)) end as 'avg_temp', 
    case 
    when tmin is null then 'No data' else cast(tmin as varchar(50)) end as 'Minimum Temperature', 

Data Type Precedence (Transact-SQL)

+0

落とし穴の感謝を。 – robot

関連する問題