我有下表 -
Customer ID | Year | Category | Value
---------------|-----------|-----------------|----------
100 | 2014 | Poor | 10
100 | 2014 | Mediocre | 20
100 | 2014 | Brilliant | 80
100 | 2014 | Poor | 10
100 | 2014 | Brilliant | 80
100 | 2014 | Naive | 15
100 | 2014 | Exceptional | 100
100 | 2014 | Neutral | 40
100 | 2015 | Brilliant | 80
100 | 2015 | Poor | 10
200 | 2014 | Exceptional | 100
200 | 2015 | Neutral | 40
现在我想添加一个额外的列'分数'到这张桌子。列中的值应基于'类别'柱。
总的来说,我有6个这样的条件
所以结果表应该是 -
Customer ID | Year | Category | Value | Score
--------------|-----------|-----------------|----------|--------
100 | 2014 | Poor | 10 | 15
100 | 2014 | Mediocre | 20 | 15
100 | 2014 | Brilliant | 80 | 75
100 | 2014 | Poor | 10 | 15
100 | 2014 | Brilliant | 80 | 75
100 | 2014 | Naive | 15 | 10
100 | 2014 | Exceptional | 100 | 75
100 | 2014 | Neutral | 40 | 75
100 | 2015 | Brilliant | 80 | NULL
100 | 2015 | Poor | 10 | NULL
200 | 2014 | Exceptional | 100 | Null
200 | 2015 | Neutral | 40 | Null
SQL小提琴表 - http://sqlfiddle.com/#!9/470a7/1
答案 0 :(得分:0)
这应该这样做:
SELECT *,
CASE
WHEN Category = 'Poor' AND EXISTS(
SELECT * FROM Table t1
WHERE t1.CustomerID=t.CustomerID
AND t1.Year=t.Year
AND t1.Category='Naive'
) THEN 10
WHEN Category = 'Naive' AND EXISTS(
SELECT * FROM Table t1
WHERE t1.CustomerID=t.CustomerID
AND t1.Year=t.Year
AND t1.Category='Poor'
) THEN 10
WHEN Category = 'Poor' AND EXISTS(
SELECT * FROM Table t1
WHERE t1.CustomerID=t.CustomerID
AND t1.Year=t.Year
AND t1.Category='Mediocre'
) THEN 15
WHEN Category = 'Mediocre' AND EXISTS(
SELECT * FROM Table t1
WHERE t1.CustomerID=t.CustomerID
AND t1.Year=t.Year
AND t1.Category='Poor'
) THEN 15
WHEN Category IN ('Brilliant','Exceptional','Neutral') AND (
SELECT COUNT(DISTINCT Category) FROM Table t1
WHERE t1.CustomerID=t.CustomerID
AND t1.Year=t.Year
AND t1.Category IN ('Brilliant','Exceptional','Neutral')
)=3 THEN 75
END AS Score
FROM Table t
ORDER BY CustomerID, Year