带有双别名表的连接的SQL语句问题

时间:2013-03-28 13:49:01

标签: sql sql-server

我不确定如何标题这个问题,下面是我想要做的一个例子,它创建两个值总和高于阈值的东西,一个用于下面但是这两个陈述是彼此排斥的。我认为使用左连接或左边连接可能会起作用。有什么想法吗?

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 

1 个答案:

答案 0 :(得分: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表,除非您将其用于过滤目的。