SQL Analyse if Farmer has Animal -


i want make table this:

person      animal   farmer 1    horse   farmer 2    horse   farmer 4    horse   farmer 1    sheep   farmer 3    sheep   farmer 4    sheep   farmer 2    cow   farmer 3    cow   .... 

a table this

........................horse  sheep  cow   farmer 1............1..........1........0   farmer 2............1..........0........1   farmer 3............0..........1........1 

so if farmer has animal table should contain 1, otherwise 0. of course should work more farmers , animals.

i appreciate if me, totally new sql... guess should work pivot , exists stupid write correct query.

edit:

is possible add second header? if have third column "location" in original table, "house" sheeps, "garden" horses etc... want have in final table corresponding location above animal row. first column farmers, first row location, second row animal , there 0th , 1th depending if farmer has animal or not. want insert row after having final table.

select     person     ,sum(case when animal = 'horse' 1 else 0 end) horse     ,sum(case when animal = 'sheep' 1 else 0 end) sheep     ,sum(case when animal = 'cow' 1 else 0 end) cow     table group     person 

whether use pivot or conditional aggregation need know values in animal column unless want use dynamic sql means dynamically build statement similar this.


Comments