给出表'x':
Source Dest Type
A B 2
A D 2
B C 2
现在我希望源和目标的总数除去匹配的..
上述示例之一:对于类型2,Count将为4,即Count(A,B,C,D)
我试过了:
select Count(distinct Source), Count(distinct destination),Count(distinct source)+Count( distinct destination),Type
from X
where Type=2 and Src NOT IN (select destination
from X
where Type=2)
我需要为所有类型简化此查询。
如果有任何办法我可以告诉我。
谢谢!
答案 0 :(得分:1)
SELECT COUNT(DISTINCT a), Type
FROM (
SELECT DISTINCT Source AS a, Type
FROM x
UNION ALL
SELECT DISTINCT Dest AS a, Type
FROM x
)
GROUP By Type
内部联合查询将您的两个单独列转换为单个列,然后外部查询获取该联合结果,并按类型对各个值进行计数。
答案 1 :(得分:0)
试试这个:
SELECT COUNT(xxx.a) as TotalCount
FROM
(SELECT source a, type FROM tableX
UNION
SELECT dest a, type FROM tableX) xxx
WHERE xxx.Type = 2
答案 2 :(得分:0)
效率低下的方法是执行以下操作
SELECT
distinctMatches.type AS type,
COUNT(DISTINCT distinctMatches.name) AS quantity
FROM
(
(
SELECT DISTINCT
type,
source AS name
FROM x
)
UNION DISTINCT
(
SELECT DISTINCT
type,
destination AS name
FROM x
)
) AS distinctMatches
GROUP BY distinctMatches.type
这将为您的示例数据提供1行类型2和数量4
在一个理想的世界中,我会看一下数据库设计,因为它感觉好像应该分成多个表,即一个用于源(因为你似乎将“源”和“目的地”分组,这表明它们是有效的同一个项目)。如果您能够进一步规范化设计,这种类型的查询将更容易更有效地进行