SQL query problem

后端 未结 4 1932
孤独总比滥情好
孤独总比滥情好 2020-12-18 14:21

Let´s say I have two tables, \"Garden\" and \"Flowers\". There is a 1:n-relationship between these tables, because in a garden can be many flowers. Is it possible to write a

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 14:22

    Look at using Pivot in SQL Server. Here is a good link that goes over how it works:

    http://www.kodyaz.com/articles/t-sql-pivot-tables-in-sql-server-tutorial-with-examples.aspx

    Ok, i think i got it working. Try this:

    with temp as
    (
        select 'myGarden' as name, 'test1' as flower
        union
        select 'myGarden','test2'
        union
        select 'myGarden','test5'
        union
        select 'abeGarden','test4'
        union
        select 'abeGarden','test5'
        union 
        select 'martinGarden', 'test2'
    )
    
    select* from temp
    pivot
    (
      max(flower)
      for flower in (test1,test2,test3,test4,test5)
    ) PivotTable
    

    You could also make the values in the in clause dynamic. Since this is a CTE i can't in my example.

提交回复
热议问题