【发布时间】:2015-08-14 21:20:48
【问题描述】:
所以我有我的“牧师”表:
CREATE TABLE Chaplaincy_Chaplains
(
ChaplainID INTEGER IDENTITY PRIMARY KEY,
ChaplainName VARCHAR(50),
FaithID INTEGER,
Telephone VARCHAR(50),
Email VARCHAR(255),
Notes VARCHAR(255),
FOREIGN KEY (FaithID) REFERENCES Chaplaincy_Faiths(FaithID)
);
我在其中插入了四条记录:
INSERT INTO Chaplaincy_Chaplains
VALUES ('Robin Richardson',1,'555-123456','Robin.Richardson@chaplaincy.com',NULL)
INSERT INTO Chaplaincy_Chaplains
VALUES ('Peter Jackson',8,'555-123-456','Peter.Jackson@chaplaincy.com',NULL)
INSERT INTO Chaplaincy_Chaplains
VALUES ('Harry Davidson',1,'555-123-456','Harry.Davidson@chaplaincy.com',NULL)
INSERT INTO Chaplaincy_Chaplains
VALUES ('Steve Morrison',7,'555-123-456','Steve.Morrison@chaplaincy.com',NULL)
目前我已将这些记录硬编码到我的“Rota”查询中:
SELECT RotaDate, DateDay, SlotTypeID, SlotDescription AS Hours,
max(case when ChaplainName = 'Robin Richardson' then AvailabilityDescription end) Robin ,
max(case when ChaplainName = 'Peter Jackson' then AvailabilityDescription end) Peter ,
max(case when ChaplainName = 'Harry Davidson' then AvailabilityDescription end) Harry ,
max(case when ChaplainName = 'Steve Morrison' then AvailabilityDescription end) Steve
FROM Chaplaincy_Rota,Chaplaincy_Availability, Chaplaincy_Chaplains, Chaplaincy_Dates, Chaplaincy_Faiths, Chaplaincy_SlotTypes
WHERE
RotaDate = Chaplaincy_Dates.Date AND
RotaSlot = SlotTypeID AND
RotaChaplain = ChaplainID AND
RotaAvailability = AvailabilityID AND
ChaplainFaith = Chaplaincy_Faiths.FaithID
GROUP BY RotaDate, SlotTypeID, SlotDescription, DateDay
ORDER BY RotaDate, SlotTypeID;
这给了我这样的东西:
| Robin | Peter | Harry | Steve |
01/06/2015 | Mon | 00:00 to 08:00 | Leave | Study | On-call | Avail |
01/06/2015 | Mon | 08:00 to 13:00 | Leave | Study | On-call | Avail |
01/06/2015 | Mon | 13:00 to 18:00 | Leave | Study | On-call | Avail |
01/06/2015 | Mon | 18:00 to 00:00 | Leave | Study | On-call | Avail |
02/06/2015 | Tue | 00:00 to 08:00 | On-call| Avail | Study | Avail |
02/06/2015 | Tue | 08:00 to 13:00 | On-call| Avail | Study | Avail |
02/06/2015 | Tue | 13:00 to 18:00 | On-call| Avail | Avail | Avail |
02/06/2015 | Tue | 18:00 to 00:00 | On-call| Avail | Avail | Avail |
....
et cetera
有没有一种方法可以动态更新我的“Rota”查询,这样每次我在“Chaplains”表中添加一条新记录时,该记录都会自动包含在“Rota”查询中?实际上,我希望能够向“Rota”查询添加一列,只需向 Chaplains 表添加一行即可。
非常感谢您的阅读!
【问题讨论】:
-
是的,有办法。寻找动态查询和
EXEC函数 -
您要么需要使用动态 SQL,要么最好在表示层中进行数据透视。关于这个有很多问题 - 搜索
dynamic pivot(或搜索bluefeet)
标签: sql-server variables dynamic parameters