我正在寻找一种使用'lookup'表来获取颜色值的方法。 请参阅以下两个表中的示例并查找结果。
表格列和值:
ColumnName | Condition | CellColor
Rank | > 90 | Green
Rank | between 70 and 89 | Yellow
Rank | < 70 | Red
Score | > 89 | Purple
Score | < 88 | Orange
人员表
Name | Rank | Score
Jane | 100 | 50
John | 77 | 90
Kelly| 50 | 99
我想要的结果
PersonnelName | Rank | RankCellColor | Score | Scoredcolor
Jane | 100 | Green | 50 | Orange
John | 77 | Yellow | 90 | Purple
Kelly | 50 | Red | 99 | Purple
我试图遍历列排名和分数,但却陷入了如何使用条件的困境。我迷失了编码。 我真的需要帮助来解决这个问题。
任何帮助都将不胜感激!!
答案 0 :(得分:0)
SQL不适合此类问题。您可以将条件表结构为:
ColumnName, Lower, Upper, CellColor
Rank, 90, NULL, Green
Rank, 70, 89, Yellow
Rank, NULL, 70, Red
Score, 89, NULL, Purple
Score, NULL, 88, Orange
然后您的查询将如下所示:
select p.*, cr.color as rankcolor, cs.color as scorecolor
from personnel p left join
conditions c
on cr.columnname = 'Rank' and
(p.rank >= cr.lower or cr.lower is null) and
(p.rank <= cr.upper or cr.upper is null) left join
conditions cs
on cs.columnname = 'Score' and
(p.score >= cs.lower or cs.lower is null) and
(p.score <= cs.upper or cs.upper is null);
答案 1 :(得分:0)
如果指定颜色的下限和上限,这将更容易。 您可以加入值,其值在下限和上限范围内。
CREATE TABLE Conditions (ColumnName varchar(50), minval int, maxval int, CellColor varchar(50))
INSERT INTO Conditions
VALUES
('Rank', 90, 100, 'Green')
,('Rank', 70, 89, 'Yellow')
,('Rank', 0, 70, 'Red')
,('Score', 89, 100, 'Purple')
,('Score', 0, 88, 'Orange')
CREATE TABLE Personnel (Name varchar(50), Rank int, Score int)
INSERT INTO Personnel
VALUES
('Jane', 100, 50)
,('John', 77, 90)
,('Kelly', 50, 99)
SELECT P.Name, P.Rank, ConRank.CellColor, P.Score, ConScore.CellColor
FROM Personnel P
INNER JOIN Conditions ConRank
ON P.Rank >= ConRank.minval AND P.Rank <= ConRank.maxval AND ConRank.ColumnName = 'Rank'
INNER JOIN Conditions ConScore
ON P.Score >= ConScore.minval AND P.Score <= ConScore.maxval AND ConScore.ColumnName = 'Score'
ORDER BY P.Name
提供输出:
Name Rank CellColor Score CellColor
Jane 100 Green 50 Orange
John 77 Yellow 90 Purple
Kelly 50 Red 99 Purple
引用此sqlfiddle:http://sqlfiddle.com/#!6/15f3a/6