date - SQL get the latest record -


i struggeling here pull out 2 results table. have table different types, items , values added on different dates.

type item value date 1    10   111   20160101 1    10   122   20170101 1    11   222   20170101 1    12   312   20170101 2    10   144   20160101 2    10   155   20170101 2    11   105   20160101 2    11   133   20170101 2    11   123   20180101 3    10   111   20170101 

first lastest date, show on combination of type, item. have tried query, show me dates.

select type, item, value, max(date) date tablename type='1' or type='2' group type, item, value 

below like.

type item value date 1    10   122   20170101 1    11   222   20170101 1    12   312   20170101 2    10   155   20170101 2    11   123   20180101 

then have more tricky question, here totally lost , not sure if possible, or maybe should in other way? see if item type 1 has value, while type 2 has not. or other way around. displayed in new table.

item type1 type2 date 10   1     2     20170101 -> item 10 has values both type 1,2 on specific date 11   1           20170101 -> item 11 has value when type 1 on specific date 11         2     20180101 -> item 11 has value when type 2 on specific date 12   1           20170101 -> item 12 has value when type 1 on specific date 

for first question think can use:

select a.type, a.item, a.value, a.date  tablename inner join on (select type, item, max(date) maxdate                 tablename                 group type, item) b on a.type = b.type , a.item = b.item , a.date=b.maxdate a.type='1' or a.type='2' 

for second try this:

select distinct a.item, b.type type1, c.type type2, case when b.type not null b.dat else c.dat end date_x       (select item, type, max(date) dat      item      group item, type)      left join (select item, type, max(date) dat item type='1' group item, type) b on a.item = b.item , a.dat= b.dat      left join (select item, type, max(date) dat item type='2' group item, type) c on a.item = c.item , a.dat= c.dat 

output :

    item    type1   type2   date_x 1   10  1   2   20170101 2   11  null    2   20180101 3   11  1   null    20170101 4   12  1   null    20170101 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -