我正在使用SQL Sever数据库,我正在编写一个查询来选择每个选项的计数&#RecordDate在调查的开始和结束日期中找到。如果相同的任何选项在开始和日期之间发现多次,那么即使这样也应该考虑一次。
tblOptions
----------------------------------
Option, RecardDate
----------------------------------
o1 , 2016-01-01
o1 , 2016-01-03
o1 , 2016-05-08
o2 , 2016-01-04
o2 , 2016-01-01
o2 , 2016-01-23
o2 , 2016-05-15
o3 , 2016-05-01
o3 , 2016-05-02
o3 , 2016-05-03
o3 , 2016-04-04
o3 , 2016-08-04
tblSurveys
----------------------------------
Surey, StartDate, EndDate
----------------------------------
s1 , 2016-01-01 , 2016-01-15
s2 , 2016-01-16 , 2016-01-31
s3 , 2016-05-01 , 2016-05-31
输出
Option, Count
-------------------
o1, 2 (Exp.:o1's recorddates found between two surveys star and end dates)
o2, 3 (Exp.:o2's recorddates found between three surveys star and end dates)
o3, 1 (Exp.:o3's recorddates found between one surveys star and end dates)
答案 0 :(得分:0)
您可以通过将数据加在一起然后将它们组合在一起(下面的distinct
选项)来实现这一目标,这样您就可以计算出独特的组合:
select [Option] -- You really should try to avoid using reserved
,count(1) as [Count] -- words for your column names.
from (
select distinct o.[Option]
,s.Survey
,s.StartDate
,s.EndDate
from @tblOptions o
inner join @tblSurveys s
on(o.RecardDate between s.StartDate and s.EndDate)
) a
group by [Option]
答案 1 :(得分:0)
使用COUNT(DISTINCT column)
SELECT
o.[Option], COUNT(DISTINCT Survey) [Count]
FROM
tblOptions o
INNER JOIN
tblSurveys s ON o.RecardDate BETWEEN s.StartDate AND s.EndDate
GROUP BY
o.[Option]