简体   繁体   中英

How to Join SQL Table Content having 2 primary keys?

I have two SQL Tables in my database

Structure of table1 is ie customer_classification is

 CREATE TABLE IF NOT EXISTS `customer_classification` ( `sid` int(5) NOT NULL, `customer_id` varchar(15) NOT NULL, `classification` varchar(5) NOT NULL, `appendix_id` int(5) NOT NULL, `bill_date` date NOT NULL ); 

Structure of table2 is ie customer_consumption is

 CREATE TABLE IF NOT EXISTS `customer_consumption` `sid` int(5) NOT NULL, `customer_id` varchar(25) NOT NULL, `bill_date` date NOT NULL, `reading` float NOT NULL, `consumption` float NOT NULL, `energy_bill` float NOT NULL, `meter_rent` float NOT NULL, `arrear` float NOT NULL ); 

In both tables, primary keys are customer_id and bill_date , because in a particular month there is only bill corresponding to single customer.

Now, my problem is, I am not able to merge these tables data into one to display the whole record.

I have tried this Sql Query, have a look

select co.customer_id, co.reading, co.consumption, cl.classification
from   customer_consumption as co
INNER JOIN customer_classification as cl
   on cl.customer_id = co.customer_id
      and month(cl.bill_date) = month(co.bill_date)
where  month(co.bill_date) = month(now())

It is not giving me the accurate result

I am going to guess that the consumption table has records for each month and the classification record only has records when the classification changes. If so, you want to get the most recent classification. And you can do that as:

select co.customer_id, co.reading, co.consumption,
       (select cl.classification
        from customer_classification as cl
        where cl.customer_id = co.customer_id and
              cl.bill_date <= co.bill_date
        order by cl.bill_date desc
        limit 1
       ) as classification
from   customer_consumption co
where  month(co.bill_date) = month(now());

Try this SQL query

select co.customer_id, sum(co.reading), sum(co.consumption), cl.classification
from   customer_consumption as co
INNER JOIN customer_classification as cl
   on cl.customer_id = co.customer_id
      and month(cl.bill_date) = month(co.bill_date)
where  month(co.bill_date) = month(now())
group by co.customer_id

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