如何在超级查询中使用子查询的结果?

时间:2015-03-12 20:21:04

标签: mysql sql sqlite

我试图在多个表的场景中找到平均年龄。问题是年龄是从出生日期计算的派生属性。现在我写了以下查询,其中包含满足条件的所有人的年龄。现在我想找到所有这些的平均年龄,但我不知道如何在超级查询中使用子查询的结果。

查询是:

Select  
    case
        when date(dob, '+' ||
            (strftime('%Y', 'now') - strftime('%Y', dob)) ||
            ' years') <= date('now')
        then strftime('%Y', 'now') - strftime('%Y', dob)
        else strftime('%Y', 'now') - strftime('%Y', dob) - 1
    end
    as age
from UserProfile where User_ID in
(Select User_ID from UserProfile
where User_ID IN
(Select Channel_ID
from Channels
where Channel_Type = 'Public-Channel'
group by Channel_ID
HAVING (SUM(LENGTH(Video_IDs) - LENGTH(REPLACE(Video_IDs, ',', '')) + 1)) > 4));

输出是所有年龄段的一列列表,你能告诉我如何计算平均年龄,因为这是我唯一想要展示的东西。

1 个答案:

答案 0 :(得分:6)

如果我理解正确,你只需要一个简单的数字作为最终结果。你可以再上一层来找到平均年龄。

SELECT avg(age) FROM (
Select  
    case
        when date(dob, '+' ||
            (strftime('%Y', 'now') - strftime('%Y', dob)) ||
             ' years') <= date('now')
         then strftime('%Y', 'now') - strftime('%Y', dob)
         else strftime('%Y', 'now') - strftime('%Y', dob) - 1
     end
     as age
 from UserProfile where User_ID in
 (Select User_ID from UserProfile
 where User_ID IN
 (Select Channel_ID
from Channels
  where Channel_Type = 'Public-Channel'
 group by Channel_ID
 HAVING (SUM(LENGTH(Video_IDs) - LENGTH(REPLACE(Video_IDs, ',', '')) +      1)) > 4)))