如果有超过x然后声明

时间:2012-08-07 13:54:06

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

有没有HAVING和WHERE条款相互猜想?即伪代码:

CASE
   HAVING count(children) > 3 THEN WHERE nationality = 'Mexican'
   HAVING count(children) = 2 THEN WHERE nationality = 'American'
   HAVING count(children) = 1 THEN WHERE nationality = 'Japanese'
END

4 个答案:

答案 0 :(得分:1)

您可以将查询包装在另一个SELECT

SELECT *
FROM
(
    SELECT count(children) as ChildrenCount, nationality 
    FROM yourTable
    GROUP BY nationality 
) x
WHERE 
    (ChildrenCount > 3 AND nationality = 'Mexican')
    OR
    (ChildrenCount = 2 AND nationality = 'American')
    OR
    (ChildrenCount = 1 AND nationality = 'Japanese')

答案 1 :(得分:1)

你想要的逻辑是什么?

让我猜你想要墨西哥人超过3个孩子,美国人有2个孩子,日本人有1个。在这种情况下,你会想要:

having (case when count(nationality = 'Mexican' then children end) > 3 then 'true'
             when count(nationality = 'American' then children end) = 2 then 'true'
             when count(nationality = 'Japanese' then children end) = 1 then 'true'
        end) = 'true'

然而,即使这看起来很奇怪。你为什么算“孩子”。你在忙什么?如果children只是数据中的一个字段,那么这应该是WHERE子句而不是HAVING子句:

where (nationality = 'Mexican' and children end > 3) or
      (nationality = 'American' and children = 2) or
      (nationality = 'Japanese' and children = 1)

答案 2 :(得分:0)

您可以将现有查询包装在CTE中以将计数和分组与过滤分开,然后使用CASE中的最终WHERE子句中的CTE计数:

;WITH [Counts] AS
(
    SELECT
        ,nationality
        ,COUNT(children) AS [children]
    FROM
        xyz
    GROUP BY
        nationality
)
SELECT
    *
FROM
    [Counts]
WHERE 
    nationality = 
    (
        CASE 
            WHEN [children] > 3 THEN 'Mexican'
            WHEN [children] = 2 THEN 'American'
            WHEN [children] = 1 THEN 'Japanese' 
        END
    )

答案 3 :(得分:0)

这应该工作

DECLARE @table TABLE     
(    
     nationality varchar (25),  
     totalchildren int
)   

insert @table  
    SELECT nationality,COUNT(children) AS totalchildren 
    FROM TABLENAME
    GROUP BY nationality

SELECT
    *
FROM
    @table  
WHERE 
    nationality = 
    (
        CASE 
            WHEN totalchildren > 3 THEN 'Mexican'
            WHEN totalchildren = 2 THEN 'American'
            WHEN totalchildren = 1 THEN 'Japanese' 
        END
    )