从SQL查询中获取true / false

时间:2014-10-08 14:59:51

标签: sql

我需要确定客户是否使用SQL查询购买了100种或更多独特的饮料,到目前为止我已经做过:

     SELECT COUNT(DISTINCT beer_id)
     FROM Orders
     WHERE patron_email='smith@gmail.com'

我如何测试这个结果是100还是更多?

更新:对于模糊的问题,我很抱歉,我需要使用标准的SQL。

7 个答案:

答案 0 :(得分:2)

使用having子句,如:

SELECT COUNT(DISTINCT beer_id)
FROM Orders
WHERE patron_email='smith@gmail.com'
having count(distinct beer_id) > 100

答案 1 :(得分:2)

您可以将CASE与产生单行的子查询一起使用:

SELECT CASE WHEN (SELECT COUNT(DISTINCT beer_id)
                 FROM Orders
                 WHERE patron_email='smith@gmail.com') > 100 
                 THEN 'More than 100' ELSE 'Not more than 100' END As ColumnName

答案 2 :(得分:2)

这适用于MySQL,不确定其他人:

 SELECT COUNT(DISTINCT beer_id) > 100
 FROM Orders
 WHERE patron_email='smith@gmail.com'

SELECT中添加一个布尔条件。它将评估为0表示false或1表示true。

答案 3 :(得分:1)

试试这个:

SELECT COUNT(beer_id)
     FROM Orders
     WHERE patron_email='smith@gmail.com'
group by beer_id
having COUNT(beer_id) > 100

答案 4 :(得分:1)

或另外一个:

select case when (count(distinct beer_id)>100) then 1
        else 0 end
    from orders where patron_email='.....'

答案 5 :(得分:1)

假设T-SQL

DECLARE @result AS INT
DECLARE @boolean AS INT

SET @result = ( SELECT COUNT(DISTINCT beer_id)
                FROM Orders
                WHERE patron_email='smith@gmail.com')

IF @result > 100
    BEGIN
        SET @boolean = 1
    END
ELSE
    BEGIN
        SET @boolean = 0
    END             

答案 6 :(得分:1)

EXISTS运算符产生一个布尔值:

SELECT EXISTS (
    SELECT 12345
    FROM orders
    GROUP BY customer_id
    HAVING COUNT(beer_id) > 100
    ) AS at_least_one_customer_ordered_100_different_beers
    ;