是否有更好的方法来执行这样的查询:
SELECT COUNT(*)
FROM (SELECT DISTINCT DocumentId, DocumentSessionId
FROM DocumentOutputItems) AS internalQuery
我需要数一下这个表中不同项的数量,但不同项超过两列。
我的查询工作得很好,但我想知道我是否可以只使用一个查询(不使用子查询)得到最终结果
是否有更好的方法来执行这样的查询:
SELECT COUNT(*)
FROM (SELECT DISTINCT DocumentId, DocumentSessionId
FROM DocumentOutputItems) AS internalQuery
我需要数一下这个表中不同项的数量,但不同项超过两列。
我的查询工作得很好,但我想知道我是否可以只使用一个查询(不使用子查询)得到最终结果
当前回答
若要作为单个查询运行,请连接列,然后获取连接的字符串的不同实例计数。
SELECT count(DISTINCT concat(DocumentId, DocumentSessionId)) FROM DocumentOutputItems;
在MySQL中,你可以做同样的事情,而不需要下面的连接步骤:
SELECT count(DISTINCT DocumentId, DocumentSessionId) FROM DocumentOutputItems;
MySQL文档中提到了这个特性:
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_count-distinct
其他回答
当我在谷歌上搜索我自己的问题时,发现如果你计算DISTINCT对象,你会得到正确的返回数(我使用MySQL)
SELECT COUNT(DISTINCT DocumentID) AS Count1,
COUNT(DISTINCT DocumentSessionId) AS Count2
FROM DocumentOutputItems
您不喜欢现有查询的哪些方面?如果您担心两列之间的DISTINCT不返回唯一的排列,为什么不试试呢?
在Oracle中,它当然可以像您所期望的那样工作。
SQL> select distinct deptno, job from emp
2 order by deptno, job
3 /
DEPTNO JOB
---------- ---------
10 CLERK
10 MANAGER
10 PRESIDENT
20 ANALYST
20 CLERK
20 MANAGER
30 CLERK
30 MANAGER
30 SALESMAN
9 rows selected.
SQL> select count(*) from (
2 select distinct deptno, job from emp
3 )
4 /
COUNT(*)
----------
9
SQL>
edit
我进入了分析的死胡同,但答案很明显……
SQL> select count(distinct concat(deptno,job)) from emp
2 /
COUNT(DISTINCTCONCAT(DEPTNO,JOB))
---------------------------------
9
SQL>
编辑2
对于以下数据,上面提供的串联解决方案将会计数错误:
col1 col2
---- ----
A AA
AA A
所以我们要包含分隔符…
select col1 + '*' + col2 from t23
/
显然,所选择的分隔符必须是一个字符或一组字符,它不能出现在任何一列中。
若要作为单个查询运行,请连接列,然后获取连接的字符串的不同实例计数。
SELECT count(DISTINCT concat(DocumentId, DocumentSessionId)) FROM DocumentOutputItems;
在MySQL中,你可以做同样的事情,而不需要下面的连接步骤:
SELECT count(DISTINCT DocumentId, DocumentSessionId) FROM DocumentOutputItems;
MySQL文档中提到了这个特性:
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_count-distinct
希望这能起作用,我正在prima vista上写
SELECT COUNT(*)
FROM DocumentOutputItems
GROUP BY DocumentId, DocumentSessionId
你的查询没有问题,但你也可以这样做:
WITH internalQuery (Amount)
AS
(
SELECT (0)
FROM DocumentOutputItems
GROUP BY DocumentId, DocumentSessionId
)
SELECT COUNT(*) AS NumberOfDistinctRows
FROM internalQuery