0

在我的数据库中,我可以很容易地看到我的表中的最后 50 个人,state=NY 和 postcode=12405,我可以查看表以查看他们是否有狗。

    SELECT state, postcode, havedog
    FROM address
    WHERE (state=NY) AND (postcode=12405)
    ORDER BY surname DESC
    LIMIT 0 , 5

哪个返回

state   postcode    havedog
NY  12405   yes
NY  12405   yes
NY  12405   no
NY  12405   no
NY  12405   yes

我还可以计算我的整个数据库中有多少人有一只狗,其中 state=NY 和 postcode=12405

    SELECT state, postcode COUNT(havedog) AS DOG
    FROM address
    WHERE (state=NY AND postcode=12405 ) AND (havedog=yes)

但是我不知道如何限制计数,所以它只计算 state=NY 和 postcode=12405 和 havedog=yes 的最后 5 条记录,是否可以对 Count 函数应用限制?

例如,鉴于上表,我的计数结果应该是 3。

4

3 回答 3

1

使用子选择:

SELECT COUNT(*) FROM
(
    SELECT state, postcode, havedog
    FROM address
    WHERE state = 'NY' AND postcode = 12405
    ORDER BY surname DESC
    LIMIT 5
) T1
WHERE havedog = 1
于 2012-12-02T07:47:37.330 回答
0

你可以这样做:

SELECT
  state,
  postcode
  COUNT(havedog) AS DogCounts
FROM
(
  SELECT state, postcode, havedog
  FROM address
  WHERE (state=NY) AND (postcode=12405)
  ORDER BY surname DESC
  LIMIT 50
) t
GROUP BY state, postcode
于 2012-12-02T07:47:48.373 回答
0
SELECT top 50 state, postcode, COUNT(havedog) OVER () AS DOG
FROM address 
WHERE (state='NY' AND postcode=12405 ) AND (havedog='yes')
于 2012-12-02T07:49:41.927 回答