sql - MySQL Custom calculate views -


i having difficulty trying combine set of queries using. having execute multiple queries different years , cid numbers. (cid 1-5, years currentyear currentyear-6)

current sql statement:

select  1 cid, 2015 `year`, (   select sum( legacy_reports_payments.amountpaid ) * -1 payments  legacy_reports_payments       datepaid >= "2015-01-01 00:00:00"   , datepaid < "2015-02-01 00:00:00"     , cid = 1) paymentsjan, (   select sum( legacy_reports_payments.amountpaid ) * -1 payments  legacy_reports_payments       datepaid >= "2015-02-01 00:00:00"   , datepaid < "2015-03-01 00:00:00"     , cid = 1) paymentsfeb, (   select sum( legacy_reports_payments.amountpaid ) * -1 payments  legacy_reports_payments       datepaid >= "2015-03-01 00:00:00"   , datepaid < "2015-04-01 00:00:00"     , cid= 1) paymentsmar, ... 

this returns:

cid  | year | paymentsjan | paymentsfeb | ... 1    | 2015 | 3000.00     | 3000.00     | ... 

i want create single view can show of calculated information, instead of running several queries 1 above. have view more this:

cid   | year | paymentsjan | paymentsfeb | ... 1     | 2015 | 3000.00     | 3000.00     | ... 2     | 2015 | 2000.00     | 2000.00     | ... 3     | 2015 | 5000.00     | 5000.00     | ... 1     | 2014 | 1000.00     | 3000.00     | ... 2     | 2014 | 3000.00     | 4000.00     | ... 3     | 2014 | 2000.00     | 5000.00     | ... 

can provide insight on best way handle this?

you build temporary table years , cids need , join query on of them @ one. many sub queries slow, better doing each 1 manually.

create table #dates ( controlcid int ,controlyear varchar(4) )  declare @year int = year( getdate() ) declare @numyears int = 6 declare @numcid int = 5 declare @cidcounter int  while (@numyears > 0) begin     set @cidcounter = @numcid      while (@cidcounter > 0)     begin         insert #dates values ( @cidcounter,  (@year - @numyears + 1))          set @cidcounter = @cidcounter - 1     end      set @numyears = @numyears -1 end  select controlcid     ,controlyear     --,(   select sum( legacy_reports_payments.amountpaid ) * -1 payments  legacy_reports_payments     --where   p.datepaid >= (controlyear+'-01-01 00:00:00')   , p.datepaid < (controlyear+'-02-01 00:00:00')     --and p.cid = controlcid) paymentsjan,        --etc , on...  #dates  order controlyear desc, controlcid   drop table #dates 

just use year , cid table in sub queries , should go.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -