我有这张表
CREATE TABLE [dbo].[Room] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (32) NOT NULL,
[Capacity] TINYINT NOT NULL,
[CapacityOccupied] TINYINT NOT NULL,
CONSTRAINT [PK_Room] PRIMARY KEY CLUSTERED ([Id] ASC)
);
表中的数据是:
。
我使用查询查找状态容量,如下所示:
如果房间已满,则显示
如果房间为空,则显示空
我使用此查询但是,我不知道如何显示可用容量。
SELECT CASE
WHEN (Capacity-CapacityOccupied)= Capacity
THEN 'Empty'
when (Capacity-CapacityOccupied)=0
then 'Full'
END as Salable, *
FROM Room
结果是:
第2,3,4行 - >如何展示免费容量? 例如: - 空 - 3 - 2 - 1 - 完整
答案 0 :(得分:1)
尝试:
SELECT
CASE
WHEN (Capacity-CapacityOccupied)= Capacity
THEN 'Empty'
WHEN (Capacity-CapacityOccupied)=0
THEN 'Full'
ELSE
CAST((Capacity-CapacityOccupied) AS nvarchar(100))
END AS Salable, *
FROM Room
答案 1 :(得分:1)
尝试这种方式:
SELECT CASE
WHEN (Capacity-CapacityOccupied)= Capacity
THEN 'Empty'
when (Capacity-CapacityOccupied)=0
then 'Full'
else cast((Capacity-CapacityOccupie) as varchar(10))
END as Salable, *
FROM Room
答案 2 :(得分:1)
只需添加Else
即可。此外,Case
可以简化:
SELECT CASE
WHEN CapacityOccupied = 0
THEN 'Empty'
when Capacity = CapacityOccupied
then 'Full'
Else Cast(Capacity - CapacityOccupied As Varchar (5))
END as Salable, *
FROM Room
答案 3 :(得分:0)
您需要在CASE中添加默认值。
你正在达到你的条件,但你需要在它没有完全满或完全空的时候迎合这个条件。
修改强>
在END
之前添加ELSE 然后'部分占领'