我在尝试编写查询时遇到问题。
我的表格如下:
tblTicketIssues
TicketID | RequesterID
tblPersonnelProfile
PersonnelID | FirstName | LastName
tblTicketAttribute
TicketID | Attribute | AttributeValue
我必须显示以下字段:
TicketID,
RequesterFullName,
UrgentPriorityID,
MediumPriorityID,
LowPrioritytID
这是具有挑战性的部分:
如果tblTicketAttribute.Attribute = “紧急”然后从价值 tblTicketAttribute.AttributeValue是 显示在UrgentPriority列
中如果tblTicketAttribute.Attribute = “中”然后是来自的价值 tblTicketAttribute.AttributeValue是 显示在MediumPriority列
中如果tblTicketAttribute.Attribute =“Low” 那么价值来自 tblTicketAttribute.AttributeValue是 显示在LowPriority列
中
tblTicketAttribute.Attribute
中的值包括“紧急”,“中等”,“低”,“超过30 “,”超过60 “,”超过90 “,”关闭“
我该怎么做?
答案 0 :(得分:5)
查看CASE声明。
select
ticketID
,Lastname +', '+firstname
,CASE attribute
WHEN 'Urgent' THEN attributeValue
ELSE ''
END as UrgentPriorityID
,CASE attribute
WHEN 'Medium' THEN attributeValue
ELSE ''
END as MediumPriorityID
,CASE attribute
WHEN 'Low' THEN attributeValue
ELSE ''
END as LowPrioritytID
from
...
答案 1 :(得分:3)
我假设RequestorID
是PersonnelID
中tblPersonnelProfile
主键的外键。这应该适用于SQL Server
SELECT
issues.TicketID,
personnel.FirstName + ' ' + personnel.LastName AS RequesterFullName,
CASE WHEN attribute.Attribute = 'Urgent' THEN attribute.AttributeValue ELSE NULL END AS UrgentPriorityID,
CASE WHEN attribute.Attribute = 'Medium' THEN attribute.AttributeValue ELSE NULL END AS MediumPriorityID,
CASE WHEN attribute.Attribute = 'Low' THEN attribute.AttributeValue ELSE NULL END AS LowPrioritytID
FROM
tblTicketIssues issues
INNER JOIN
tblPersonnelProfile personnel
ON
issues.RequestorID = personnel.PersonnelID
INNER JOIN
tblTicketAttribute attribute
ON
issues.TicketID = attribute.TicketID
答案 2 :(得分:0)
使用jms或Russ所做的CASE
语句可能是更好的方法,但你也可以使用子选择来解决问题:
SELECT ti.TicketID,
pp.FirstName || ' ' || pp.LastName AS RequesterFullName,
(SELECT ta.AttributeValue FROM tblTicketAttribute AS ta WHERE ta.Attribute = 'Urgent' AND ta.TicketID = ti.TicketID) AS UrgentPriorityID,
(SELECT ta.AttributeValue FROM tblTicketAttribute AS ta WHERE ta.Attribute = 'Medium' AND ta.TicketID = ti.TicketID) AS MediumPriorityID,
(SELECT ta.AttributeValue FROM tblTicketAttribute AS ta WHERE ta.Attribute = 'Low' AND ta.TicketID = ti.TicketID) AS LowPriorityID
FROM tblTicketIssues AS ti
INNER JOIN tblPersonnelProfile AS pp ON ti.RequestorID = pp.PersonnelID;
我怀疑CASE
会更快,但在你测量之前你永远都不会知道,有时候亚选择方法是你唯一的选择。如果WHERE
谓词为假,您将在子选择列中自动获取NULL。
此外,您还可以看到格式化SQL查询的整个方法,以及更多的Oracle-ish连接运算符。
我还应该提一下,如果tblTicketAttribute中的TicketID列不是唯一的,则子选择将不起作用,但如果是这种情况,其他选项也可能会产生不稳定的结果。