0

我不知道如何命名这个问题,下面是我想要做的一个例子,它是创建两个超过阈值的总值和一个低于阈值的值,但是这两个语句是相互排斥的。我认为使用左连接或左连接可能会起作用。请问有什么想法吗?

SELECT Count(Sale1.id) above500, 
       Count(sale2.id) below500, 
       employee.name 
FROM   employeesale es 
       INNER JOIN employee 
               ON es.employeeid = employee.id 
       LEFT JOIN sale Sale1 
              ON es.saleid = sale1.id 
       LEFT JOIN sale Sale2 
              ON es.saleid = sale2.id 
WHERE  Sale1.value >= 500 
       AND Sale2.value < 500 
4

1 回答 1

7

你不需要两个连接。进行条件聚合:

SELECT sum(case when sale.value >= 500 then 1 else 0 end) as above500, 
       sum(case when sale.value < 500 then 1 else 0 end) as below500, 
       employee.name 
FROM   employeesale es 
       INNER JOIN employee 
               ON es.employeeid = employee.id 
       LEFT JOIN sale
              ON es.saleid = sale.id 
group by employee.name

我添加了group by条款。此外,您似乎不需要employeesale 表,除非您将其用于过滤目的。

于 2013-03-28T13:52:22.773 回答