数数' HAVING'所有记录都有列=''

时间:2015-04-12 00:33:06

标签: mysql count having

这是我的查询...我正在尝试找到所有拥有多个容器的BLNUMBERS,其中所有容器都是' status =''。为什么这不起作用?我现在正在买一些所有容器的BLNUMBERS。 status =''还有一些地位<>''编辑:我如何找到BLNUMBERS哪里有一些容器' status =''和一些容器'状态<> ''

 SELECT
     DISTINCT
     BLNUMBER
     #,CONTAINERNUMBER
     ,COUNT(CONTAINERNUMBER) AS COUNT
 FROM   
     SHIPMENTS
 WHERE
      BLNUMBER <> ''
      AND CDATE > NOW() - INTERVAL 1 MONTH
      AND CDATE < NOW() - INTERVAL 7 DAY
      AND CONTAINERNUMBER <> ''
      AND CONTAINERNUMBER NOT LIKE '.AIR%'
      AND CONTAINERNUMBER NOT LIKE 'AIR%'
      AND CARRIER_ID <>8
      AND STATUS = ''
  GROUP BY 
      BLNUMBER
  HAVING
      COUNT > 1

2 个答案:

答案 0 :(得分:1)

因此,如果我理解正确,您想要选择BLNUMBERS CONTAINER的{​​{1}} BLNUMBER为空STATUS的所有BLNUMBERS,这意味着您要排除CONTAINER至少有一个STATUS非空CONTAINER

为此,我会根据BLNUMBER计算CONTAINER s的总数,然后计算每STATUS个空白BLNUMBER的总数BLNUMBERS,然后只返回总CONTAINER次数等于空白CONTAINER s的SELECT totalBlanks.BLNUMBER, totalBlanks.`count` FROM (SELECT BLNUMBER, COUNT(*) `count` FROM SHIPMENTS GROUP BY BLNUMBER) totals LEFT JOIN (SELECT BLNUMBER, COUNT(*) `count` FROM SHIPMENTS WHERE `STATUS` = '' GROUP BY BLNUMBER) totalBlanks ON totals.BLNUMBER = totalBlanks.BLNUMBER WHERE totals.`count` = totalBlanks.`count`

所以

{{1}}

答案 1 :(得分:1)

以下查询获取具有任何容器且没有状态的所有BLNUMBER

SELECT DISTINCT BLNUMBER
FROM SHIPMENTS
WHERE BLNUMBER <> '' AND
      CDATE > NOW() - INTERVAL 1 MONTH AND
      CDATE < NOW() - INTERVAL 7 DAY AND
      CONTAINERNUMBER <> '' AND
      CONTAINERNUMBER NOT LIKE '.AIR%' AND
      CONTAINERNUMBER NOT LIKE 'AIR%' AND
      CARRIER_ID <> 8 
GROUP BY BLNUMBER, CONTAINERNUMBER
HAVING MAX(STATUS) > '';

要获得具有多个容器的容器需要额外级别的子查询:

SELECT BLNUMBER
FROM (SELECT BLNUMBER, CONTAINERNUMBER
      FROM SHIPMENTS
      WHERE BLNUMBER <> '' AND
            CDATE > NOW() - INTERVAL 1 MONTH AND
            CDATE < NOW() - INTERVAL 7 DAY AND
            CONTAINERNUMBER <> '' AND
            CONTAINERNUMBER NOT LIKE '.AIR%' AND
            CONTAINERNUMBER NOT LIKE 'AIR%' AND
            CARRIER_ID <> 8 
      GROUP BY BLNUMBER, CONTAINERNUMBER
      HAVING MAX(STATUS) > ''
     ) b
GROUP BY BLNUMBER
HAVING COUNT(*) >= 2;