[英]SQL look up table with condition column
I'm looking for a way to use a 'lookup' table to get the color values. 我正在寻找一种使用“查找”表来获取颜色值的方法。 See my examples below of the two tables and results in looking for.
请参阅下面两个表的示例,并查找结果。
Table columns and values: 表列和值:
ColumnName | Condition | CellColor
Rank | > 90 | Green
Rank | between 70 and 89 | Yellow
Rank | < 70 | Red
Score | > 89 | Purple
Score | < 88 | Orange
Personnel Table 人事表
Name | Rank | Score
Jane | 100 | 50
John | 77 | 90
Kelly| 50 | 99
Results I want to get 我想得到的结果
PersonnelName | Rank | RankCellColor | Score | Scoredcolor
Jane | 100 | Green | 50 | Orange
John | 77 | Yellow | 90 | Purple
Kelly | 50 | Red | 99 | Purple
I've tried to loop through the columns Rank and Score, but get stuck on how to use the condition. 我尝试遍历“等级”和“得分”列,但在使用条件时会遇到困难。 I get lost in coding this.
我迷上了编码。 I really need help in figuring this out.
我真的需要帮助弄清楚这一点。
Any help would be appreciated!! 任何帮助,将不胜感激!!
SQL is not suited to this type of problem. SQL不适合这种类型的问题。 You could structure the conditions table as:
您可以将条件表的结构如下:
ColumnName, Lower, Upper, CellColor
Rank, 90, NULL, Green
Rank, 70, 89, Yellow
Rank, NULL, 70, Red
Score, 89, NULL, Purple
Score, NULL, 88, Orange
Then your query would look like: 然后您的查询将如下所示:
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);
If you specify lower and upper limits for the color this will be much easier. 如果您指定颜色的上限和下限,这将更加容易。 You can join the table where the values fall within the ranges of the lower and upper limits.
您可以将值落入上下限范围的表合并。
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
Gives output: 给出输出:
Name Rank CellColor Score CellColor
Jane 100 Green 50 Orange
John 77 Yellow 90 Purple
Kelly 50 Red 99 Purple
Reference this sqlfiddle: http://sqlfiddle.com/#!6/15f3a/6 引用此sqlfiddle: http ://sqlfiddle.com/#!6/15f3a/6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.