我正在使用SQL Server 2012.我的SQL遵循以下结构。
SELECT A.attributeA
,A.attributeB
,Count(A.*) AS CountA -- I know this is wrong.
,Count(B.*) AS CountB
FROM
(
SELECT ... FROM Foo1
) A
FULL OUTER JOIN
(
SELECT ... FROM Foo2
) B
ON A.attribute1 = B.attribute1
GROUP BY
A.attributeA
,A.attributeB
我想从子查询A和B中获取所有行的计数。我该怎么做?先感谢您。
答案 0 :(得分:0)
假设目标是仅计算连接每一侧的非空记录,您可以指定您希望非空的列名(如注释中所述),通常与列中的列相同你的加入。例如,因为您加入了attribute1:
SELECT A.attributeA
,A.attributeB
,Count(A.attribute1) AS CountA
,Count(B.attribute1) AS CountB
FROM
...
请注意,这不会告诉您2重叠的时间,如果这是您的目标的一部分。对于这种类型的计数,您可以使用SUM结合CASE:
SELECT A.attributeA
,A.attributeB
,Count(A.attribute1) AS CountA
,Count(B.attribute1) AS CountB
,SUM(CASE WHEN A.attribute1 IS NOT NULL AND B.attribute1 IS NOT NULL
THEN 1 ELSE 0
END) as CountAAndBOverlap
FROM
...
答案 1 :(得分:0)
如果您的目的只是获取两个子查询的计数,您可以执行类似这样的操作。我还为这两个子查询生成了常见的ID
,以便我JOIN
。最后,我使用了INNER JOIN
代替FULL JOIN
。
SELECT
CountSubqueryA AS CountA,
CountSubqueryB AS CountB
FROM
(SELECT 1 AS ID,COUNT(*) AS CountSubqueryA FROM Foo1 ) AS A
INNER JOIN
(SELECT 1 AS ID,COUNT(*) AS CountSubqueryB FROM Foo2 ) AS B
ON A.ID=B.ID
答案 2 :(得分:0)
我看到了你的GROUP BY
,想到也许你想要这个。它最多可以创建3个组,如下所示:
==========================
| A | NOT B | 24 |
--------------------------
| NOT A | B | 31 |
--------------------------
| A | B | 69 |
==========================
SELECT
CASE WHEN A.attribute1 IS NOT NULL THEN 'A' ELSE 'NOT A' END,
CASE WHEN B.attribute1 IS NOT NULL THEN 'B' ELSE 'NOT B' END
COUNT(*)
FROM
(
SELECT ... FROM Foo1
) A
FULL OUTER JOIN
(
SELECT ... FROM Foo2
) B
ON A.attribute1 = B.attribute1
GROUP BY
CASE WHEN A.attribute1 IS NOT NULL THEN 'A' ELSE 'NOT A' END,
CASE WHEN B.attribute1 IS NOT NULL THEN 'B' ELSE 'NOT B' END