2

一部のデータの取得に問題があります。私は4つのテーブルを持ってい
ます
user_profile
user_income
tax_category

各ユーザーに適用される税カテゴリを選択する必要があります。そのために、2つのクエリがあります

1 つ目はユーザーの合計収入と年齢を選択し、2 つ目はユーザーに適用される税カテゴリを選択します。しかし、これを1つのクエリに変換できませんでした

SELECT userid,user_profile_gender,date_part('years',age(user_profile_dob))+1 AS userage,incomeresult.totalincome FROM user
LEFT JOIN user_profile ON user_profile_userid = user.userid 
INNER JOIN 
        (SELECT SUM(income_amount) totalincome, income_userid FROM user_income
        WHERE income_date BETWEEN '2012-03-30' AND '2014-03-30' 
        GROUP BY income_userid) AS incomeresult ON user.userid = incomeresult.income_userid     
WHERE user.status = 1

SELECT * FROM tax_category
WHERE 70 BETWEEN taxcategory_agefrom AND taxcategory_ageto AND taxcategory_gender=1 AND 12000 BETWEEN taxcategory_incomefrom AND taxcategory_incometo

2 番目のクエリ では、 from 、from 、およびfrom70の値を指定する必要があります。 そのようなクエリを作成することは可能ですか? PostgreSQL 8.4 を使用していますuserage1user_profile_gender12000incomeresult.totalincome

4

2 に答える 2

2

CTE構文を使用できると思います:

WITH A AS
(  
SELECT 
  userid,
  user_profile_gender,
  date_part('years',age(user_profile_dob))+1 AS userage,
  incomeresult.totalincome 
FROM 
  user
  LEFT JOIN user_profile ON user_profile_userid = user.userid 
  INNER JOIN 
        (SELECT SUM(income_amount) totalincome, income_userid FROM user_income
        WHERE income_date BETWEEN '2012-03-30' AND '2014-03-30' 
        GROUP BY income_userid) AS incomeresult ON user.userid = incomeresult.income_userid     
WHERE 
  user.status = 1
)
SELECT * 
FROM 
  tax_category
  INNER JOIN A 
WHERE A.userage BETWEEN taxcategory_agefrom AND taxcategory_ageto AND taxcategory_gender=1 AND A.totalincome BETWEEN taxcategory_incomefrom AND taxcategory_incometo
于 2013-07-17T12:45:31.247 に答える
2
select
    userid,
    user_profile_gender,
    date_part('years', age(user_profile_dob)) + 1 as userage,
    incomeresult.totalincome,
    tax_category.*
from
    user
    left join
    user_profile on user_profile_userid = user.userid 
    inner join 
        (
            select sum(income_amount) totalincome, income_userid
            from user_income
            where income_date between '2012-03-30' and '2014-03-30' 
            group by income_userid
        ) as incomeresult on user.userid = incomeresult.income_userid
    left join
    tax_category on 
        date_part('years', age(user_profile_dob)) + 1 between taxcategory_agefrom and taxcategory_ageto
        and taxcategory_gender = 1
        and totalincome between taxcategory_incomefrom and taxcategory_incometo
where user.status = 1
于 2013-07-17T12:40:36.800 に答える