Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>SELECT column_date, MAX(CASE WHEN supplier = 'XY' AND location = 'A wing' THEN qty END) AS 'XY A wing', MAX(CASE WHEN supplier = 'XY' AND location = 'B wing' THEN qty END) AS 'XY B wing', MAX(CASE WHEN supplier = 'CD' AND location = 'A wing' THEN qty END) AS 'CD A wing', MAX(CASE WHEN supplier = 'CD' AND location = 'B wing' THEN qty END) AS 'CD B wing', MAX(CASE WHEN supplier = 'AB' AND location = 'A wing' THEN qty END) AS 'AB A wing', MAX(CASE WHEN supplier = 'AB' AND location = 'B wing' THEN qty END) AS 'AB B wing' FROM @t GROUP BY column_date </code></pre> <h2><a href="http://data.stackexchange.com/stackoverflow/query/75130" rel="nofollow">DEMO</a></h2> <p><strong>Update:</strong> What you are looking for here is how to <a href="http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx" rel="nofollow"><em>pivot</em></a> your columns, but the problem with your query is there is no aggregate column you can aggregate the other columns with when you <code>GROUP BY column_date</code>. Since you need to <code>GROUP BY column_date</code>, then the other columns need to either be in the <code>GROUP BY clause</code> or contained in a an aggregate function. Therefore I used an aggregate function <code>MAX</code> as a work around. This is fine if you know the values you want to pivot forehand. But if you want to pivot unknown or changing number of values, then you need to do this dynamically. Try to search for <em>Dynamic Pivoting in SQL Server</em> and you will find a lot of workarounds using dynamic SQL. For example see these two articles:</p> <ul> <li><a href="http://www.codeproject.com/Articles/27776/Dynamic-Pivoting-in-SQL-Server" rel="nofollow">Dynamic Pivoting in SQL Server.</a></li> <li><a href="http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables" rel="nofollow">Dynamic Cross-Tabs/Pivot Tables.</a></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload