我有两个看起来像这样的表:
Rep Client ID #
-------------------
Bob 100
Joe 200
Joe 201
Dave 300
Dave 301
Rep Client ID #
----------------
Jack 100
Joe 200
Joe 400
Dave 300
Dave 500
我需要做两件事:
计算每个表中为每个rep分配的客户端数(ID#)。例如。对于表1,它将是Bob有1,Joe有2,Dave有2。
从两个表中计算每个代表共有多少个UNIQUE客户端。在上面的例子中,Bob有1,Joe有3,Dave有3,Jack有1。
我该怎么办?
答案 0 :(得分:0)
您需要GROUP BY
/ Totals
查询。对于您的第一个要求,
SELECT
Rep,
Count(ClientID) As CountOfID
FROM
Table1
GROUP BY
Rep;
满足您的第二个要求。你需要一个带GROUP BY的UNION。
SELECT
TmpQ.Rep,
Count(TmpQ.ClientID) As CountOfID
FROM
(
SELECT
Table1.Rep,
Table1.ClientID
FROM
Table1
GROUP BY
Table1.Rep,
Table1.ClientID
UNION
SELECT
Table2.Rep,
Table2.ClientID
FROM
Table2
GROUP BY
Table2.Rep,
Table2.ClientID
) As TmpQ
GROUP BY
TmpQ.Rep;
答案 1 :(得分:0)
要获得每张桌子每个代表的不同clientids的数量,您可以使用:
SELECT
sourcetable,
rep,
count(clientid)
FROM
(
SELECT
"table 1" as [sourcetable],
rep,
clientid
FROM
table1
GROUP BY 1,2,3
)
UNION ALL
SELECT
sourcetable,
rep,
count(clientid)
FROM
(
SELECT
"table 2" as [sourcetable],
rep,
clientid
FROM
table2
GROUP BY 1,2,3
)
为了获得每个代表的不同clientids的数量而不考虑表:
SELECT
rep,
count(clientid)
FROM
(
SELECT rep,clientid FROM table1
UNION
SELECT rep,clientid FROM table2
)
GROUP BY 1