简体   繁体   English

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

[英]How to use results of a sub-query in a super query?

I am trying to find the average age in a scenario of multiple tables. 我试图在多个表的情况下找到平均年龄。 The problem is that age is a derived attribute calculated from date of birth. 问题在于,年龄是从出生日期算起的派生属性。 Now I have written the following query which has the age of all the people that meet the condition. 现在,我写了以下查询,其中列出了所有符合条件的人的年龄。 Now I want to find the average age of all of these but I am not sure how to use the results of the sub-query in the super-query. 现在,我想找到所有这些对象的平均年龄,但是我不确定如何在超级查询中使用子查询的结果。

The query is: 查询是:

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));

And the output is a one column list of all ages, can you tell me how to calculate the average age because that's the only thing I want to display. 输出是所有年龄段的一列列表,您能告诉我如何计算平均年龄,因为这是我要显示的唯一内容。

If I understand correctly, you just want one simple number as the end result. 如果我理解正确,那么您只想要一个简单的数字作为最终结果。 You can just go up one more level to find the average age. 您可以再升一级以找到平均年龄。

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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM