在我的数据库中,我可以很容易地看到我桌上的最后50个人状态= NY和邮编= 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
我还可以统计我的整个数据库中有多少人有一只狗,其中州=纽约,邮政编码= 12405
SELECT state, postcode COUNT(havedog) AS DOG
FROM address
WHERE (state=NY AND postcode=12405 ) AND (havedog=yes)
但是我无法弄清楚如何限制计数,因此它只计算最近5条记录,其中state = NY,postcode = 12405和havedog = yes,是否可以对Count函数应用限制?
例如,如上表所示,我的计数结果应为3。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
SELECT top 50 state, postcode, COUNT(havedog) OVER () AS DOG
FROM address
WHERE (state='NY' AND postcode=12405 ) AND (havedog='yes')