一个值与其他值不同时的情况,SQL Server [英] Case when a value is different to other value, SQL Server

查看:88
本文介绍了一个值与其他值不同时的情况,SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有表prices的这种表结构:

I have this table structure for table prices:

CREATE TABLE prices
(
     id int, 
     priceFrom int, 
     priceUp int
);

INSERT INTO prices (id, priceFrom, priceUp)
VALUES (1, 23, 23), (2, 0, 0), (3, 12, 13),
       (4, 40, 40), (5, 15, 15), (6, 0, 0);

这是结果:

我有这个查询:

select 
    pricefrom, priceup,
    case
        when pricefrom = 0 then null
        when priceFrom <> priceUp then priceFrom + ' - ' + priceUp
        when priceFrom = priceUp then priceFrom
    end as FinalPrice
from 
    prices

我需要做的是

  1. pricefrom = 0,然后显示空
  2. pricefrom = priceup然后显示价格
  3. 至少如果pricefrom!= priceup我想显示例如:12(pricefrom)-13(pr​​iceup)

但在我的查询中此行:

我尝试使用<>进行此操作,但结果显示两个数字的总和:

I try to do this with <> but in the result appears the sum for both numbers:

我该如何解决?

推荐答案

我认为您正在这里寻找 concat 函数.

I think you're looking for the concat function here.

 select pricefrom, priceup,
case
when pricefrom = 0 then null
when priceFrom <> priceUp then concat(priceFrom, ' - ', priceUp)
when priceFrom = priceUp then cast(priceFrom as varchar(8))
end as FinalPrice
from prices

此链接可能会有所帮助

MySQL将两列合并为一列

这篇关于一个值与其他值不同时的情况,SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆