我有Table PREV:
Client Ctg
1 CC
1 OVD
2 CC
3 OVD
和表ACT:
Client Ctg
1 OVD
2 CC
4 OVD
我需要计算每个产品的两个表之间的差异(有多少客户离开了产品,有多少是新产品)
因此结果应该是CC -1,OVD -1新的OVD 1
这些结果可以有两种不同的选择
我试过了:
从PREV中选择count(*),在client = client where中加入ACT cliet是Ctg
的空组
但当一个客户有更多产品时,这不起作用......:/
请注意,有数千个客户,每个客户最多可以有5个产品(Ctg)
另外每个月(ACT和PREV就像2月/ 1月)是留下的客户和新客户。在最终形式中,我也想计算新的。
答案 0 :(得分:1)
如果您想要一个表中的记录数而不是另一个表中的记录数,请在它们之间进行左/右连接并计算空值的数量。 IE:
SELECT a.Ctg, a.Client PrevClient, b.Client ActClient
FROM PREV a
LEFT JOIN ACT b ON a.Client = b.Client AND a.Ctg = b.Ctg
所以现在ActClient将为空,其中PREV表中的记录不在ACT表中。然后,您可以通过将SQL包装在另一个SQL语句中来简单地获取计数。 IE
SELECT Ctg, COUNT(*) FROM (
SELECT a.Ctg, a.Client PrevClient, b.Client ActClient
FROM PREV a
LEFT JOIN ACT b ON a.Client = b.Client AND a.Ctg = b.Ctg
) Tmp
WHERE ActClient IS NULL
GROUP BY Ctg
因此,为了获得ACT中不在PREV中的记录计数,您可以简单地使用具有RIGHT联接的相同查询。并将a.Ctg
更改为b.Ctg
答案 1 :(得分:0)
select a.ctg,a.sum2-b.sum1 from
(select ctg, count(*) sum2 from prev group by ctg)a,
(select act.ctg ctg, count(*) sum1 from prev join act
on prev.client=act.client and prev.ctg=act.ctg group by act.ctg)b;
答案 2 :(得分:0)
cte正在计算PREV计数,然后与当前计数进行比较。
; with cte
as
( select prev.Ctg, COUNT(ctg) as prevCount
from PREV
group by prev.Ctg
)
SELECT ACT.Ctg , COUNT(act.ctg) - cte.prevCount as Difference, COUNT(act.ctg) as CurrentCount, cte.prevCount as PrevCount
from ACT
join cte
on act.Ctg = cte.Ctg
group by ACT.Ctg, cte.prevCount
答案 3 :(得分:0)
基本版:
SELECT COUNT(*) FROM [ACT] as a
where not exists (select * from [PREV] as p
where a.Client = p.Client and a.Ctg = p.Ctg)
好的,所以试试这个:
select a.Ctg, COUNT(a.Client) as ClientCoutThatAddThatCategory
from ACT as a
left outer join PREV as p
on a.Client=p.Client and a.Ctg=p.Ctg
where p.Client is NULL
group by a.Ctg
select p.Ctg, COUNT(p.Client) as ClientCoutThatLeftThatCategory
from ACT as a
right outer join PREV as p
on a.Client=p.Client and a.Ctg=p.Ctg
where a.Client is NULL
group by p.Ctg