首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在TSQL中选择行作为视图列?

如何在TSQL中选择行作为视图列?
EN

Stack Overflow用户
提问于 2016-04-22 11:33:52
回答 1查看 50关注 0票数 2

假设我有3个表:AnimalCareTakerApppointment。模式,其中包含一些数据,如:

代码语言:javascript
复制
Create Table Animal (Id int identity, Name varchar(25))
Create Table CareTaker(Id int identity, Name varchar(50))
Create Table Appointments(Id int identity, AnimalId int, CareTakerId int, AppointmentDate DateTime, BookingDate DateTime)

Insert into Animal(Name) Values('Ghost'), ('Nymeria'), ('Greywind'), ('Summer')
Insert into CareTaker(Name) Values ('Jon'), ('Arya'), ('Rob'), ('Bran') 

Insert into Appointments(AnimalId, CareTakerId, AppointmentDate, BookingDate) Values
(1, 1, GETDATE() + 7, GetDate()), -- Ghost cared by Jon
(1, 2, GETDATE() + 6, GetDate()), -- Ghost cared by Arya
(4, 3, GETDATE() + 8, GetDate()) -- Summer cared by Rob

我只想为每只动物选择3名管理员作为一个栏。就像这样:

我不关心其他的约会,只关心接下来的三个,每只动物。如果没有三个约会,则可以为空/空。

我很困惑该怎么做。

我尝试过使用Sub查询,如下所示:

代码语言:javascript
复制
select Name, 
    -- Care Taker 1
    (Select Top 1 C.Name
    From Appointments A
        Join CareTaker C on C.Id = A.CareTakerId
    Where A.AppointmentDate > GETDATE()
        And A.AnimalId = Animal.Id
    Order By AppointmentDate) As CareTaker1,
    -- Appointment Date 1
    (Select Top 1 AppointmentDate
    From Appointments
    Where AppointmentDate > GETDATE()
        And AnimalId = Animal.Id
    Order By AppointmentDate) As AppointmentDate1
From Animal

但是对于第二个看门人,我将不得不在where子句上进行第二级select,以将id从前1中排除(因为不确定如何获得第二行),类似于select top 1 after excluding first row id; where first row id is (select top 1)情景。

不管怎样,这看起来不是一个很好的方法。

我怎样才能得到想要的输出?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-22 11:45:20

您可以使用以下方法获取行中的所有信息:

代码语言:javascript
复制
select an.name as animal, ct.name as caretaker, a.appointmentdate
from appointments a join
     animals an
     on a.id = an.animalid join
     caretaker c
     on a.caretakerid = c.id;

然后,你基本上想要把它转成支点。一种方法使用pivot关键字。另一个条件聚合。我更喜欢后者。对于这两种方法,您都需要一个枢轴列,它使用row_number()提供。

代码语言:javascript
复制
select animal,
       max(case when seqnum = 1 then caretaker end) as caretaker1,
       max(case when seqnum = 1 then appointmentdate end) as appointmentdate1,
       max(case when seqnum = 2 then caretaker end) as caretaker2,
       max(case when seqnum = 2 then appointmentdate end) as appointmentdate2,
       max(case when seqnum = 3 then caretaker end) as caretaker3,
       max(case when seqnum = 3 then appointmentdate end) as appointmentdate3
from (select an.name as animal, ct.name as caretaker, a.appointmentdate,
             row_number() over (partition by an.id order by a.appointmentdate) as seqnum
      from appointments a join
           animals an
           on a.id = an.animalid join
           caretaker c
           on a.caretakerid = c.id
     ) a
group by animal;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36792764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档