今天我正在处理一个SQL查询,我只想在得到查询中所示的差值后得到计数,但是它显示了多余的计数值。请解释这是怎么回事?
select ((select count(city) from station) - (select count(distinct city) from station))
from station;
当我使用独特的方法时,问题就解决了。 因此请帮助我更好地理解SQL查询。
答案 0 :(得分:2)
如果您只希望两个子查询的计数之间有一个差异,请尝试从<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:apply-templates select="/skills/skill[not(employee)]" />
</xsl:template>
<xsl:template match="skill">
<xsl:param name="employee" select="/skills/skill[id=current()/id and name=current()/name and employee]" />
<xsl:choose>
<xsl:when test="count($employee) > 0">
<xsl:for-each select="$employee">
<xsl:value-of select="id" /> | <xsl:value-of select="name" /> | <xsl:value-of select="employee" />
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="id" /> | <xsl:value-of select="name" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
表中进行选择:
dual
但是实际上,您甚至可以根本不用子查询来完成此操作:
SELECT
(SELECT COUNT(city) FROM station) - (SELECT COUNT(DISTINCT city) FROM station) AS diff
FROM dual;
答案 1 :(得分:0)
通过减少Select子句的数量,您可以采用不同的方法。
尝试以下操作:
SELECT derived_t.total_city_count - derived_t.unique_city_count AS difference
FROM
(
SELECT COUNT(city) AS total_city_count,
COUNT(DISTINCT city) AS unique_city_count
FROM station
)