我现在已经尝试了几个小时才能返回,第四行会告诉我doman_namn的数量。我一直在尝试添加一个COUNT(DISTINCT doman_namn),但后来我需要一个group by,这反过来会破坏目的。
这是存储过程,它带有两个参数:
@keyword[varchar](100),
@domannamn [varchar](100)
它使用两个看起来像这样的表
第一表 table t_doman 列; doman_id doman_name
第二桌 table t_ranking 列; ranking_position ranking_date ranking_keyword ranking_id_doman
我使用@keyword在t_ranking表中查找正确的行,然后我在doman_id上的ranking_id_doman上加入以获取“doman_name”,每个日期都会有一组名称,这反过来又会产生名称为每个日期重新考虑自己,我需要检查有多少不同的名称并连续返回。
我需要它像:
Ranking position, date, name, number of distinct name's
1___________________2012-11-11, tony, 3
2___________________2012-11-11, chris, 3
3___________________2012-11-11, peter, 3
1___________________2012-11-10, tony, 3
2___________________2012-11-10, chris, 3
3___________________2012-11-10, peter, 3
SELECT
ranking_position,
CONVERT(varchar(10),ranking_date, 120),
doman_namn
--Here's my my attempt COUNT(DISTINCT doman_namn) as 'number_of_discint_names'
FROM
(SELECT
ranking_position,
ranking_date,
ranking_id_doman
FROM dbo.t_ranking
WHERE ranking_keyword = 'keyword'
AND ranking_date BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE()
AND ranking_id_doman IN (SELECT doman_id FROM dbo.t_doman WHERE doman_namn LIKE 'doman' + '%')) as tr
JOIN dbo.t_doman td on tr.ranking_id_doman = td.doman_id
--GROUP BY doman_namn ALSO IT DOES NOT WORK
ORDER BY ranking_date ASC
答案 0 :(得分:2)
Declare
@keyword nvarchar(20) = N'keyword',
@domannamn nvarchar(20) = N'C'
Select
r.ranking_position,
r.ranking_date,
d.doman_name,
Count(r.ranking_id_doman) Over (Partition By r.ranking_date)
From
dbo.t_ranking r
inner join
dbo.t_doman d
on r.ranking_id_doman = d.doman_id
Where
ranking_keyword = @keyword And
ranking_date Between DateAdd(day, -30, GetDate()) And GetDate() And
d.doman_name like @domannamn + '%'
Order By
2, 1
http://sqlfiddle.com/#!3/ccf10/2
正如理查德指出的那样,如果您在排名日期内有重复的ranking_id_doman值并且您想要不同的值,那么这不起作用。