根据状态选择

时间:2013-03-06 19:26:44

标签: sql oracle

我有这个用于计算组件的SQL查询:

SELECT COUNT(CS.COMPONENTTYPEID) AS CNT
FROM COMPONENTTYPE CT LEFT
OUTER JOIN COMPONENTSTATS CS ON CS.COMPONENTTYPEID = CT.COMPONENTTYPEID
WHERE CT.COMPONENTTYPEID IN (?, ?)
GROUP BY CT.NAME,
         CT.COMPONENTTYPEID
ORDER BY CT.COMPONENTTYPEID

我想选择所有status = 'Active'的组件。我必须插入的正确位置在哪里?也许这个:

SELECT COUNT(CS.COMPONENTTYPEID) AS CNT
FROM COMPONENTTYPE CT LEFT
OUTER JOIN COMPONENTSTATS CS ON CS.COMPONENTTYPEID = CT.COMPONENTTYPEID
WHERE CT.COMPONENTTYPEID IN (?, ?) WHERE STATUS = 'Active'
GROUP BY CT.NAME,
         CT.COMPONENTTYPEID
ORDER BY CT.COMPONENTTYPEID

3 个答案:

答案 0 :(得分:2)

SELECT COUNT(CS.COMPONENTTYPEID) AS CNT
FROM COMPONENTTYPE CT 
    LEFT OUTER JOIN COMPONENTSTATS CS ON CS.COMPONENTTYPEID = CT.COMPONENTTYPEID AND CS.STATUS = 'Active'
WHERE CT.COMPONENTTYPEID IN (?, ?) 
GROUP BY CT.NAME, CT.COMPONENTTYPEID
ORDER BY CT.COMPONENTTYPEID

过滤器应该在join子句上,因为它用于创建连接表的结果集。

答案 1 :(得分:2)

你要么需要一个复合词,否则你就无法使用左连接..

SELECT COUNT(CS.COMPONENTTYPEID) AS CNT
FROM COMPONENTTYPE CT 
LEFT OUTER JOIN COMPONENTSTATS CS 
  ON CS.COMPONENTTYPEID = CT.COMPONENTTYPEID
WHERE CT.COMPONENTTYPEID IN (?, ?) and (STATUS = 'Active' or Status is null)
GROUP BY CT.NAME,
         CT.COMPONENTTYPEID
ORDER BY CT.COMPONENTTYPEID

或者你必须在限制条件上加上限制标准。

SELECT COUNT(CS.COMPONENTTYPEID) AS CNT
FROM COMPONENTTYPE CT 
LEFT OUTER JOIN COMPONENTSTATS CS 
  ON CS.COMPONENTTYPEID = CT.COMPONENTTYPEID
  AND (STATUS = 'Active')
WHERE CT.COMPONENTTYPEID IN (?, ?) 
GROUP BY CT.NAME,
         CT.COMPONENTTYPEID
ORDER BY CT.COMPONENTTYPEID

答案 2 :(得分:1)

由于STATUS列位于COMPONENTSTATS表中,因此查询应为

SELECT COUNT(CS.COMPONENTTYPEID) AS CNT
FROM COMPONENTTYPE CT LEFT
OUTER JOIN COMPONENTSTATS CS ON CS.COMPONENTTYPEID = CT.COMPONENTTYPEID
WHERE CT.COMPONENTTYPEID IN (?, ?) AND CS.STATUS = 'Active'
GROUP BY CT.NAME,
         CT.COMPONENTTYPEID
ORDER BY CT.COMPONENTTYPEID