2013-07-17 73 views
2

我在提取某些數據時遇到問題。我有4個表
用戶
user_profile
user_income
tax_category組合兩個查詢中的問題

,我需要選擇適用於每個用戶的稅種。爲此,我有兩個查詢

第一個選擇用戶的總收入和年齡,第二個選擇適用於用戶的稅收類別。但我卻沒有能夠將它轉換爲一個查詢

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 

在第二個查詢70應該從userage1user_profile_genderincomeresult.totalincome12000值。
是否可以創建這樣的查詢?我使用PostgreSQL 8.4

+1

確保運營商之間給出正確的終點。如果你的日期值沒有時間分量,這可能是你想要的。但是,如果存在時間分量組件,則不會包含午夜(上午12:00:00)後發生的日期爲2014-03-30的任何記錄。您可能希望使用2014-03-31減去1毫秒作爲上限。 –

回答

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