2017-01-23 55 views
1

我正在查询以获得一个分数,该分数将被添加到现有表的列中,并且仅在五个项目中至少有三项(item1 ,项目2,项目3,项目4,项目5)已完成(值为0,1或2),其他明智分数设置为缺失并设置为99. 分数=(项目值总和/有效完成项目数量)×数量项目。SQL查询根据现有列上的少数条件获取计算列

下图中的输入来自派生表。

Input and expected output

我应该如何实现查询得到预期的结果? 任何帮助将非常感激。

+0

需要更具体 – Wanderer

+0

@Ullas请你告诉我,我需要些什么提供? – mano

回答

2

试试这个:

SELECT item1, item2, item3, item4, item5, 
     CASE 
      WHEN t.n >= 3 THEN t.s/(t.n * 1.0) 
      ELSE 99 
     END AS Score 
FROM mytable 
CROSS APPLY (
    SELECT SUM(CASE WHEN item IN (0, 1, 2) THEN item ELSE 0 END), 
      COUNT(CASE WHEN item IN (0, 1, 2) THEN 1 END) 
    FROM (VALUES (item1), (item2), (item3), (item4), (item5)) AS x (item)) AS t(s, n) 
+0

谢谢,我在查询的')'末尾附近收到错误的语法,并且您在子查询(CASE WHEN IN IN(0,1,2))中使用了“item”。 请告诉我错过了什么? – mano

+0

很抱歉说“在关键字'AS'附近获得了不正确的语法。”其在这里 - > AS x(项目),我认为你的做法是优化与其他解决方案相比。 – mano

+0

@mano它现在有效! A')'丢失了。 –

2

有点不高兴不同的使用申请

with d as (
    -- sample data 
    select * 
    from (
     values 
     (1,1,2,2,4), 
     (9,1,9,9,4) 

    ) t(item1,item2,item3,item4,item5) 
) 
-- query 
select *, case when n >=3 then (s + .0)/n else 99 end score 
from d 
cross apply (
    select sum(itm) s, count(*) n from(
     select item1 itm where item1 between 0 and 2 
     union all 
     select item2 itm where item2 between 0 and 2 
     union all 
     select item3 itm where item3 between 0 and 2 
     union all 
     select item4 itm where item4 between 0 and 2 
     union all 
     select item5 itm where item5 between 0 and 2 
     ) t2 
    ) t 
3

我想什么你都呈现为表行和物品1至ITEM5是表的列。

一个非常简单和易于阅读的方法是查看项目,计数值为0,1和2的项目并将其相加。然后用这个结果来套用您的公式:

select item1, item2, item3, item4, item5, 
    case when count_items >= 3 then sum_items/count_items * 5 else 99 end 
from 
(
    select item1, item2, item3, item4, item5, 
    case when item1 in (0,1,2) then item1 else 0 end + 
    case when item2 in (0,1,2) then item2 else 0 end + 
    case when item3 in (0,1,2) then item3 else 0 end + 
    case when item4 in (0,1,2) then item4 else 0 end + 
    case when item5 in (0,1,2) then item5 else 0 end as sum_items, 
    case when item1 in (0,1,2) then 1 else 0 end + 
    case when item2 in (0,1,2) then 1 else 0 end + 
    case when item3 in (0,1,2) then 1 else 0 end + 
    case when item4 in (0,1,2) then 1 else 0 end + 
    case when item5 in (0,1,2) then 1 else 0 end as count_items 
    from mytable 
) summed; 
+0

非常感谢:) – mano

+0

乔尔乔斯给出了这样做的优化方式,所以请原谅,因此我接受他的回答 – mano

+1

不用担心;-)去你更喜欢的,并考虑更可读和更友好。我喜欢Giorgos的解决方案,但仍然更喜欢我的,因为它很容易理解。你看看它,并立即明白它是如何工作的(我认为)。但我相信很多人都喜欢Giorgos的优雅风格。 –