如何从几个表中获取COUNT?

时间:2015-11-01 01:00:19

标签: sql oracle11g

我在下面有这些数据

SCNTransformConstraint

现在我想要做的是让这个人在他/她身上有多少次OTMARK 1,也按他/她的名字分组。这就是我用于查询的内容。

TABLE 1   SID   CAMBORROW      OTMARK
          S1      CAM1           1
          S2      CAM2           1
          S3      CAM3           0

TABLE 2   SID   BOOKBORROW     OTMARK
          S1     book1           1
          S2     book2           0
          S3     book3           0

TABLE 3   SID     NAME           
          S1     SNAME1
          S2     SNAME2
          S3     SNAME3

我得到的结果远比应该发生的结果错误。我不知道哪个部分我弄错了,所以我需要帮助。提前谢谢。

编辑:期望输出

SELECT TABLE3.NAME,COUNT(*)
FROM TABLE1,TABLE2,TABLE3
WHERE TABLE3.SID = TABLE1.SID
AND   TABLE1.OTMARK = 1
OR( TABLE3.SID = TABLE2.SID
   AND TABLE2.OTMARK = 1)
GROUP BY TABLE1.NAME

3 个答案:

答案 0 :(得分:1)

您必须使用join语法join表格SELECT t3.name, sum(nvl(t1.otmark,0)+nvl(t2.otmark,0)) FROM table3 t3 left join table2 t2 on t2.sid = t3.sid and t2.otmark =1 left join table1 t1 on t1.sid = t3.sid and t1.otmark =1 where t1.otmark is not null or t2.otmark is not null GROUP BY t3.NAME

SQL Fiddle

SELECT t3.name, t1.otmark+t2.otmark
FROM  t3 
join  t2 on t2.sid = t3.sid
join  t1 on t1.sid = t3.sid
where t1.otmark > 0 or t2.otmark > 0

编辑:更简单的解决方案是

str.format()

答案 1 :(得分:0)

这是您的查询:

function convertXXXToJson(obj) {
    ... 
    return output;
}

function convertYYYToJson(obj) {
    ... 
    return output;
}

答案 2 :(得分:0)

你应该联合TABLE1和TABLE2来结合结果。

SELECT t3.NAME, COUNT(*)
FROM table3 AS t3
LEFT JOIN
  ( SELECT SID, CAMBORROW AS ITEMBORROW, OTMARK 
    FROM table1
    WHERE OTMARK = 1
    UNION ALL
    SELECT SID, BOOKBORROW AS ITEMBORROW, OTMARK 
    FROM table2
    WHERE OTMARK = 1
  ) AS t4
ON t3.SID = t4.SID
GROUP BY t3.NAME;

有关UNION语法here的更多信息。