我有一个现有的SQL Server表结构,如下所示:
--Entries Table--
*Company* | *MusicProduct* | *FoodProduct* | *PCProduct* | *PhoneProduct* |
Apple iPod null iMac iPhone
Dell null null Dellbook null
上表中的主键是Company
--Questions Table--
*ColumnName* | Questions
MusicProduct What mp3 device the company known for?
FoodProduct What food product describes the company best?
PCProduct What PC?
PhoneProduct What phone does the company give employees?
上表中的主键是ColumnName
,它包含第一个表中每个非键列的行。这当然感觉不好设计,但它预先存在我的工作。
对于选定的单一公司,我基本上想要一个返回带有问题和答案的行的查询,忽略带有空答案的问题。 Apple的输出看起来像这样(三行):
Question Answer
What mp3 device the company known for? iPod
What PC? iMac
What phone does the company give employees? iPhone
如何通过以上方式最好地实现这一目标?某种新的参考表是否可行?
答案 0 :(得分:1)
由于条目表中有固定数量的列,因此可以使用CASE
表达式从Questions表中的ColumnName列映射到要返回的列:
WITH a as(
SELECT q.Question
,CASE q.ColumnName
WHEN 'MusicProduct' THEN e.MusicProduct
WHEN 'FoodProduct' THEN e.FoodProduct
WHEN 'PCProduct' THEN e.PCProduct
WHEN 'PhoneProduct' THEN e.PhoneProduct
END as Answer
FROM Questions q
CROSS JOIN Entries
WHERE q.Company = 'Apple'
)
SELECT Question, Answer
FROM a
WHERE Answer IS NOT NULL
使用CTE可以在Answer
条件下使用WHERE
,避免在CASE
子句中重复长WHERE
个表达式,这可能会导致错误如果您需要更改其中的任何内容。
答案 1 :(得分:1)
请试一试。
select q.question, product as answer
from
(select company, Musicproduct, Foodproduct, PCProduct, phoneproduct from Entries ) p
unpivot ( product for Products in (Musicproduct, Foodproduct, PCProduct, phoneproduct)
) unpvt
join questions q on unpvt.product = q.answer;