SELECT COUNT(DISTINCT CASE WHEN a.caption = 'abc' THEN a.id END) AS "Reject",
COUNT(DISTINCT CASE WHEN b.caption ='5' THEN b.id END) AS "Dup"
FROM a with (NOLOCK) left outer join
b re with (NOLOCK)
On a.id= b.id
我想在同一个sql查询中获得两个计数的差。当我使用减号函数时,它给我错误:数据类型varchar和varchar在减运算符中不兼容。
答案 0 :(得分:1)
它应该像这样:
SELECT COUNT(DISTINCT CASE WHEN a.caption = 'abc' THEN a.id END) AS "Reject",
COUNT(DISTINCT CASE WHEN b.caption ='5' THEN b.id END) AS "Dup",
(COUNT(DISTINCT CASE WHEN a.caption = 'abc' THEN a.id END) -
COUNT(DISTINCT CASE WHEN b.caption ='5' THEN b.id END)
) as diff
FROM a LEFT JOIN
b re
ON a.id = b.id ;
除非您真的知道自己在做什么,否则不要使用WITH (NOLOCK)
。您可能会得到不一致的数据。