无论如何,有没有让 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
无论如何,有没有让 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
您可以将查询包装在另一个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')
你想要的逻辑是什么?
让我猜猜你想要有 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)
这应该有效
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
)
您可以将现有查询包装在 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
)