我有这张桌子:
table tblCountry
name char(30)
table tblSite
name char(30) primary key not null,
country char(30)
table tblDivingClub
number int
name char(30)
country char(30)
table tblDiving
diving_number int
number_of_divers int
diving_club int
guide int
我写了这个问题:
select
tblSite.name,tblSite.site_length,tblSite.site_depth,
tblSite.water_type,tblSite.country,
COUNT(distinct tblDivingClub.number) as number_of_clubs,
COUNT(distinct tblDiving.diving_number) as number_of_divings,
COUNT(distinct tblDiving.guide) as number_of_guids,
sum(tblDiving.number_of_divers) as number_of_divers
from tblCountry
inner join tblSite
on tblCountry.name=tblSite.country
inner join tblDiving
on tblSite.name = tblDiving.diving_site
inner join tblDivingClub
on tblDiving.diving_club = tblDivingClub.number
where tblSite.name in (
select tblSite.name
from tblSite
where tblSite.country = 'New York'
)
and tblDiving.date_of_diving >= DATEADD(year,-1, GETDATE())
group by tblSite.name,tblSite.site_length,tblSite.site_depth,
tblSite.water_type,tblSite.country
我想展示其中潜水量最多的月份('tblDiving.date_of_diving')和本月的分配数量。
有可能吗?
答案 0 :(得分:0)
count(distinct)
不是累积的。所以,你每个月可以有一个人参与。该月的计数为1.对于这一年,它可以是1到12之间的任何数字,具体取决于同一个人是否在多个月内潜水。
所以,你可以做你想做的事情:
select t.*
from (select tblSite.name, tblSite.site_length, tblSite.site_depth, tblSite.water_type,
tblSite.country,
COUNT(distinct tblDivingClub.number) as number_of_clubs,
COUNT(distinct tblDiving.diving_number) as number_of_divings,
COUNT(distinct tblDiving.guide) as number_of_guids,
sum(tblDiving.number_of_divers) as number_of_divers,
year(tblDiving.date_of_diving) as yr, month(tblDiving.date_of_diving) as mon,
row_number() over (partition by tblSite.name, tblSite.site_length, tblSite.site_depth, tblSite.water_type, tblSite.country
order by COUNT(distinct tblDiving.diving_number)
) as seqnum
from tblCountry inner join
tblSite
on tblCountry.name = tblSite.country inner join
tblDiving
on tblSite.name = tblDiving.diving_site inner join
tblDivingClub
on tblDiving.diving_club = tblDivingClub.number
where tblSite.name in (select tblSite.name from tblSite where tblSite.country = 'New York' ) and
tblDiving.date_of_diving >= DATEADD(year, -1, GETDATE())
group by tblSite.name, tblSite.site_length, tblSite.site_depth,
tblSite.water_type, tblSite.country,
year(tblDiving.date_of_diving), month(tblDiving.date_of_diving)
) t
where seqnum = 1;
要按年获取数据摘要,您需要将其加回原始查询。
答案 1 :(得分:0)
不确定
...
group by month(tblDiving.date_of_diving), ...
只要它只有1年的学期就会工作。如果这个报告跨越几年,你将不得不按年(),月()等分组。或者,如果你使用MSSQL 2012+,那么就有一个EOMONTH()函数。