2

我有一个查询,它使用连接的三个表中的“Case When Then End”返回结果。它看起来像这样:

select f.filename, 
sum(case when v.rUser like '%bike%' then 1 else 0 end) as bikeUser, 
sum(case when v.rUser like '%Pedestrian%' then 1 else 0 end) as pedestrianUser, 
sum(case when d.weather like '%clear%' then 1 else 0 end) as clearWeather
from VMdata v 
inner join files f on v.id = f.id
inner join DMdata d on f.id = d.id
where f.filename in (X,Y,Z)
group by f.filename 

这很好用,每个结果行都正确给出 1 或 0。这里要注意的是,每个表只有一个特定“文件名”的条目(行)。现在,当我尝试使用每个“文件名”可以有多个条目(行)的表添加另一个内部联接时,结果变得错误,只有最后一个“总和”显示正确的值,而其他“总和”给出错误价值观。第二个查询是:

select f.filename, 
sum(case when v.rUser like '%bike%' then 1 else 0 end) as bikeUser,
sum(case when v.rUser like '%Pedestrian%' then 1 else 0 end) as pedestrianUser, 
sum(case when d.weather like '%clear%' then 1 else 0 end) as clearWeather,
sum(case when m.extras like '%hat%' then 1 else 0 end) as hatExtras
from VMdata v 
inner join files f on v.id = f.id
inner join DMdata d on f.id = d.id
inner join MultiFiledata m on f.id = m.id
where f.filename in (X,Y,Z)
group by f.filename

任何想法为所有列获得正确的数字?

4

2 回答 2

1

如果MultiFiledata表可以包含表中任何对应记录的多条记录files,那么您需要在单独的查询中进行聚合并将其连接回主查询。

例如(语法可能不完美;专注于概念):

select   f.filename, 
         sum(case when v.rUser like '%bike%' 
                  then 1 else 0 end) as bikeUser,
         sum(case when v.rUser like '%Pedestrian%' 
                  then 1 else 0 end) as pedestrianUser, 
         sum(case when d.weather like '%clear%' 
                  then 1 else 0 end) as clearWeather
from     VMdata v 
         inner join files f 
         on v.id = f.id
         inner join DMdata d 
         on f.id = d.id
         inner join (
             select id, 
                    sum(case when extras like '%hat%' 
                             then 1 else 0 end) as hatExtras
             from   MultiFiledata 
         ) m 
         on f.id = m.id
where    f.filename in (X,Y,Z)
group by f.filename;
于 2012-04-23T17:18:10.327 回答
0

您的一对多连接导致总行数增加,因此当您的值 = 1 时,您将多次添加该值。为了缓解这种情况,您可能希望改用 count 函数,用它来计算不同的用户 ID。就像是:

Count(distinct case when [logic goes here] then [user ID] else null end) as bikeuser

然后,您只计算每个用户一次,而不是添加每一行。

于 2012-04-23T17:14:54.820 回答