select case when exists(
select top 1 1
from dg_world_records wr (nolock)
where wr.gametypeid = 4
and wr.playerid = 1
)
then totaltime = (select min(totaltime) from dg_world_records (nolock) where playerid = 1 and gametypeid = 4)
else totaltime = (select max(totaltime) from dg_world_records (nolock) where gametypeid = 4)
end
我的猜测是,这是无法完成的,但我正在尝试在sql case语句中进行子选择。这可能吗?
我正在尝试根据查找或未在表中查找值进行查找。我可以通过分解声明来做到这一点,但我想知道是否可以在一个声明中做到这一点。
以下是表架构:
CREATE TABLE [dbo].[DG_WORLD_RECORDS](
[WorldRecordId] [int] IDENTITY(1,1) NOT NULL,
[GameTypeId] [int] NOT NULL,
[PlayerId] [int] NOT NULL,
[NumberOfValues] [int] NOT NULL,
[TotalTime] [int] NOT NULL,
[DateOfRecord] [datetime] NOT NULL,
[GameId] [int] NULL,
[UTCInserted] [datetime] NOT NULL CONSTRAINT [DF_DG_WORLD_RECORDSII_UTCInserted] DEFAULT (getutcdate()),
[UTCUpdated] [datetime] NOT NULL CONSTRAINT [DF_DG_WORLD_RECORDSII_UTCUpdated] DEFAULT (getutcdate()),
[SrvName] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF_DG_WORLD_RECORDSII_SrvName] DEFAULT (@@servername),
CONSTRAINT [PK_DG_WORLD_RECORDS] PRIMARY KEY CLUSTERED ( [WorldRecordId] ASC ) )
答案 0 :(得分:8)
不知道你为什么写这个疯狂的查询,但回答你的问题,是的,它可以完成,只需将你的作业移出案例陈述:
select totaltime = CAST (
case when exists(
select *
from dg_world_records wr (nolock)
where wr.gametypeid = 4 and wr.playerid = 1)
then (select min(totaltime) from dg_world_records (nolock) where playerid = 1 and gametypeid = 4)
else (select max(totaltime) from dg_world_records (nolock) where gametypeid = 4)
end AS INT)