[英]Issue in combining two queries
I have an issue on fetching some data. 我在获取一些数据时遇到问题。 I have 4 tables 我有4张桌子
user 用户
user_profile 用户资料
user_income user_income
tax_category tax_category
I need to select the tax category applicable to each user. 我需要选择适用于每个用户的税种。 For that i have two queries 为此,我有两个查询
The first one select the total income and age of the user and the second one to select the tax category applicable to the user. 第一个选择用户的总收入和年龄,第二个选择适用于用户的税种。 But i was not been able convert this to one query 但是我无法将其转换为一个查询
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
In the second query 70
should be the value from userage
, 1
from user_profile_gender
and 12000
from incomeresult.totalincome
. 在第二个查询中, 70
应该是来自userage
的值,来自user_profile_gender
1
和来自incomeresult.totalincome
12000
。
Is it possible to create such a query? 是否可以创建这样的查询? I am using PostgreSQL 8.4 我正在使用PostgreSQL 8.4
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
I guess you could use CTE syntax: 我猜您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.