SQL从表中剪切结果

时间:2011-09-25 13:00:58

标签: sql

我有以下查询:

    SELECT cust_id,cust_name,SUM(calls.duration) as duration
  FROM 
      calls, telephone

  WHERE calls.from_t_no = telephone.t_no
  AND
  calls.duration <=60

  group by telephone.cust_id, telephone.cust_name

其中给出以下结果;

cust_id cust_name duration
0123456789  Avi 18
1234567890  Benny   27
2345678901  Gadi    13
3456789012  Dalia   69
4567890123  Hilla   5
5678901234  Varda   14
7890123456  Haim    20
8901234567  Tali    20
9012345678  Yoram   46

我也有这个问题:

SELECT cust_id,cust_name,SUM(calls.duration) as duration 
      FROM calls ,telephone
      WHERE to_t_no = telephone.t_no
      AND
      calls.duration >=500
      group by telephone.cust_id, telephone.cust_name

其中提供了以下结果:

cust_id cust_name   duration
2345678901  Gadi    50022
4567890123  Hilla   50000

第二个查询实际上是第一个查询应匹配的另一个过滤器或条件。 我不能在第一个查询中包含第二个查询,因为它使用不同的列。 我需要从第一个查询中“减去”第二个查询。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果您真的无法合并查询,可以像这样加入结果:

SELECT T0.cust_id, T0.cust_name, T0.duration FROM

(  SELECT cust_id,cust_name,SUM(calls.duration) as duration
FROM 
    calls, telephone

WHERE calls.from_t_no = telephone.t_no
AND
calls.duration <=60

group by telephone.cust_id, telephone.cust_name) T0

JOIN

(SELECT cust_id,cust_name,SUM(calls.duration) as duration 
  FROM calls ,telephone
  WHERE to_t_no = telephone.t_no
  AND
  calls.duration >=500
  group by telephone.cust_id, telephone.cust_name) T1

ON T0.cust_id = T1.cust_id

答案 1 :(得分:0)

尝试发布表格的完整结构并描述您真正需要的内容。

如果我理解正确的问题,您所暴露的条件是相互排斥的。我认为任何记录都不可能符合这两个条件,因为最终查询将如下所示:

SELECT cust_id,cust_name,SUM(calls.duration) as duration 
FROM calls ,telephone
WHERE 
    to_t_no = telephone.t_no
    AND calls.from_t_no = telephone.t_no
    AND calls.duration <=60
    AND calls.duration >=500
group by telephone.cust_id, telephone.cust_name;

如果你想要的是一个通用的解决方案来对查询进行“查询”你可以使用这种句子:

SELECT field1, field2 FROM
    (SELECT field1, field2, ..., fieldn FROM table WHERE condition) AS filteredTable
WHERE anyCondition;