简体   繁体   中英

SQL- Query Join 3 Tables, Group by a certain column and filter by Year?

Question:

What are the total distributions in 2020 from properties that were acquired in 2019 broken down by state?

So far this is what I have and seems like I am not getting it right to sum up? what step am I missing. I am not getting an error but not getting an answer either? Any ideas?

CREATE TABLE Property
(
    hmy INT   NOT NULL,
    scode VARCHAR   NOT NULL,
    saddr1 VARCHAR NOT NULL,
    saddr2 VARCHAR NOT NULL,
    scity VARCHAR NOT NULL,
    sstate VARCHAR NOT NULL,
    szipcode INT NOT NULL,
    PRIMARY KEY (hmy) 
);

CREATE TABLE PropInfo
(
    hmy INT   NOT NULL,
    hcode INT   NOT NULL,
    acquisitiondate DATE   NOT NULL,
    unitcount INT   NOT NULL,
    yearbuilt INT   NOT NULL,
    distributionentitycode VARCHAR   NOT NULL,
    PRIMARY KEY (hcode)
);

CREATE TABLE DistributionLog
(
    hmy INT   NOT NULL,
    hcode INT   NOT NULL,
    distributionDate DATE   NOT NULL,
    distributiontype VARCHAR   NOT NULL,
    distributionamount INT   NOT NULL,
    PRIMARY KEY (hmy)
);

SELECT SUM(DL.distributionamount) AS Total, PY.sstate, PI.acquisitiondate, DL.distributionamount 
FROM DistributionLog AS DL
JOIN PropInfo AS PI
ON PI.hmy = DL.hcode
JOIN Property AS PY
ON PY.hmy = PI.hmy
WHERE distributionDate BETWEEN '2020-1-1' AND '2020-12-31'
GROUP BY PY.sstate, PI.acquisitiondate, DL.distributionamount
ORDER BY PY.sstate;

Here's what was tried:

在此处输入图像描述

You can try something like this:

select p.sstate, sum(distributionamount)
from distributionlog d
inner join propinfo pi
  on d.hcode = pi.hcode
  and extract(year from acquisitiondate) = 2019
  and extract(year from distributiondate) = 2020
inner join property p on pi.hmy = p.hmy
group by p.sstate

In this SQL, we are joining the 3 tables as you have been doing also. We are specifying during the join to ensure that acquisition date should be in 2019 and distribution date should be from 2020.

Since you want the sum(DL.distributionamount) , DL.distributionamount should not be in group by clause. Below query should return you sstate wise sum(DL.distributionamount) for the properties that have been acquired in 2019 and distributed in 2020.(relation between tables is not clear to me without sample data. So I am assuming that you did the joining right)

SELECT  PY.sstate, SUM(DL.distributionamount) AS Total
FROM DistributionLog AS DL
JOIN PropInfo AS PI
ON PI.hmy = DL.hcode and PI.acquisitiondate BETWEEN '2019-1-1' AND '2019-12-31'
JOIN Property AS PY
ON PY.hmy = PI.hmy
WHERE distributionDate BETWEEN '2020-1-1' AND '2020-12-31'
GROUP BY PY.sstate
ORDER BY PY.sstate;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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