创建一个计算相关表中实例的查询

时间:2018-02-12 21:24:57

标签: sql oracle

我今天重写了这个查询大约20次,我一直接近但没有骰子......我确信这对于所有人来说都很容易,但我的SQL(Oracle)是很生锈。  这就是我需要的:

PersonID  Count1  Count2  Count3  Count4
1         0       0       2       1
2         1       1       1       0
3         1       1       1       2

数据来自多个来源。我有一个表人和一个表值。人们可以在该表中拥有任意数量的值。

PersonID  Item    Value
1         Check1    3
1         Check2    3 
1         Check3    4
2         Check4    2
2         Check5    3
2         Check6    1

..等等

因此,对于每个PersonID,查询将计算特定值出现的次数。值总是1,2,3或4.我尝试做4个子查询,但它不会从主查询中读取PersonID,只返回value = 1的所有实例的计数。

我当时正在考虑做一个Group_By ......我不知道。任何帮助表示赞赏!

ETA:我已删除&以多种方式多次重写查询,遗憾的是没有保存任何中间尝试。我之前没有把它包括起来,因为我正在重新安排它,并且它不能按原样运行。但现在它就像现在一样:

/*sources are the tested requirements
  values are the scores people received on the tested sources
  people are those who were tested on the requirements */

WITH sub_query4 (
    SELECT values.personid, 
        count (values.ID) as count4  --how many 4s
    FROM values 
        INNER JOIN sources ON values.valueid = sources.sourceid 
        INNER JOIN people ON people.personid = values.personid
    WHERE values.yearid = 2017  
        AND values.quarter = 'Q1'
        AND instr (sources.identifier, 'TESTBANK.01', 1 ,1) > 0
        AND values.value = '4'
    GROUP_BY people.personid
) 
SELECT p.first_name,
    p.last_name,
    p.position,
    p.email,
    p.locationid,
    sub_query4.count4 as count4   --eventually this would repeat for 1, 2, & 3
FROM people p
WHERE p.locationid=406 
    AND p.position in (9,10);

2 个答案:

答案 0 :(得分:2)

values是表的错误名称,因为它是SQL关键字。

无论如何,条件聚合应该起作用:

select personid,
       sum(case when value = 1 then 1 else 0 end) as cnt_1,
       sum(case when value = 2 then 1 else 0 end) as cnt_2,
       sum(case when value = 3 then 1 else 0 end) as cnt_3,
       sum(case when value = 4 then 1 else 0 end) as cnt_4
from values
group by personid;

答案 1 :(得分:1)

我更喜欢使用PIVOT。这是Example SQL Fiddle

SELECT "PersonID", val1,val2,val3,val4 FROM 
(
  SELECT "PersonID", "Value" from VALS
)
PIVOT 
(
     count("Value")
     FOR "Value" IN (1 as val1, 2 as val2, 3 as val3, 4 as val4)
);