我有一个名为Campaign的表。看起来像这样:
Bj::value
我想通过事件类型列中的不同值对其进行分组,然后计算事件类型中的不同值。我的桌子应该看起来像这样:
j > i
我该怎么做?
编辑14/03/19:
到目前为止我要去的地方:
website event type
amazon imp
amazon imp
amazon imp
amazon click
apple click
apple imp
adidas click
adidas imp
adidas click
adidas imp
答案 0 :(得分:4)
您可以将PIVOT
与COUNT
一起使用
DECLARE @SampleTable TABLE (website VARCHAR(10), [event type] VARCHAR(10))
INSERT INTO @SampleTable VALUES
('amazon' ,'imp'),
('amazon' ,'imp'),
('amazon' ,'imp'),
('amazon' ,'click'),
('apple' ,'click'),
('apple' ,'imp'),
('adidas' ,'click'),
('adidas' ,'imp'),
('adidas' ,'click'),
('adidas' ,'imp')
SELECT * FROM @SampleTable
PIVOT (COUNT([event type]) FOR [event type] IN ([imp], [click])) PVT
结果:
website imp click
---------- ----------- -----------
adidas 2 2
amazon 3 1
apple 1 1
答案 1 :(得分:2)
您需要条件聚合:
select website,
sum(case when event = 'imp' then 1 else 0 end) as imp,
sum(case when event = 'click' then 1 else 0 end) as click
from campaign c
group by website;
答案 2 :(得分:1)
在其他用户回答的可用其他选项中,您也可以尝试以下查询。
select a.website, imp, click from(
select website, count(eventtype) as imp
from test a where a.eventtype = 'imp' group by website
)a
inner join (
select website, count(eventtype) as click
from test b where b.eventtype = 'click' group by website
)b on a.website = b.website