使用Join和where子句计算语句

时间:2012-02-26 08:01:06

标签: sql join count

enter image description here

前两位是个别结果.. 第三个是我试图在其中加入另一个表的语句。我的问题是我无法在sql语句中设置条件。 在最后一个连接语句中,我有两个带有Route Id的列和带有Flab = 1的和,但是我无法设置flag = 0的条件..请帮助 我需要T2作为最后一列。

2 个答案:

答案 0 :(得分:5)

SELECT a.RouteCode, 
       SUM(CASE WHEN b.ScheduledFlag = '1' THEN 1 ELSE 0 END) AS T1,
       SUM(CASE WHEN b.ScheduledFlag = '0' THEN 1 ELSE 0 END) AS T2
FROM Routes a inner join CustomerVisits as b on a.RouteCode = b.RouteCode
WHERE b.RouteStartDate = '12/15/2011' 
and a.DepotCode = '6'
group by a.RouteCode

请注意,根据数据库连接的区域设置,您的日期格式字符串可能不明确。使用区域设置安全的日期格式,如ODBC规范(yyyy-mm-dd hh:mi:ss

答案 1 :(得分:1)

执行此操作的一种方法是分别创建每个计数查询,然后从每个计数查询执行左连接,以便在两个计数表中都没有匹配时不会过滤结果。

SELECT q1.routecode,
       t1,
       t2
FROM   routes
       LEFT JOIN (SELECT routecode,
                         COUNT(routecode) AS t1
                  FROM   customervisits
                  WHERE  ( routecode IN ( '701', '702', '704', '703', '705' ) )
                         AND routestartdate = '12/15/2011'
                         AND schelduledflag = '1'
                  GROUP  BY routecode) AS q1
         ON routes.routecode = q1.routecode
       LEFT JOIN (SELECT routecode,
                         COUNT(routecode) AS t2
                  FROM   customervisits
                  WHERE  ( routecode IN ( '701', '702', '704', '703', '705' ) )
                         AND routestartdate = '12/15/2011'
                         AND schelduledflag = '0'
                  GROUP  BY routecode) AS q2
         ON routes.routecode = q2.routecode
WHERE  a.depotcode = '6'  and (t1 is not null or t2 is not null);