I have results like this, the Annual
is dynamic and may have X amount of ranges
+-----------+---------+-----------+
| Annual | Revenue | Completed |
+-----------+---------+-----------+
| 2020/2021 | 1000 | Yes |
+-----------+---------+-----------+
| 2021/2022 | 2000 | Yes |
+-----------+---------+-----------+
| 2022/2023 | 2500 | No |
+-----------+---------+-----------+
I'm looking to have results like this:
+-----------+-----------+-----------+-----------+
| Annual | 2020/2021 | 2021/2022 | 2022/2023 |
+-----------+-----------+-----------+-----------+
| Revenue | 1000 | 2000 | 2500 |
+-----------+-----------+-----------+-----------+
| Completed | Yes | Yes | No |
+-----------+-----------+-----------+-----------+
Here's what I got so far, I can execute on my local but can't seem to get it to execute on sqlfiddle: http://sqlfiddle.com/#!18/a4c61/4
I've looked at examples all over stackoverflow but couldn't seem to find an exact case like mine.
Please help if you can, thank you!
Sql version: Microsoft SQL Azure (RTM) - 12.0.2000.8 May 15 2020 00:47:08
Dynamic data recommendations
You can get count and use StringBuilder
to generate strSQL
.
StringBuilder strSQL = new StringBuilder();
int DataAmount = 3;// a,b,c,d,e
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(0 ,"a");
dic.Add(1, "b");
dic.Add(2, "c");
strSQL.Append("select ");
strSQL.Append(" isnull(a.Column2,b.Column2) Column0,isnull(a.Column1,0) Column1 ");
//dic.Count > 2
for (int i = 1; i < dic.Count; i++)
{
strSQL.Append(",isnull("+dic[i]+".Column1,0) Column"+i+" ");
}
strSQL.Append(" from (SELECT ID,Column1,Column2 FROM [dbo].[20200618] UNPIVOT(Column1 for Column2 in ([Annual],[Revenue],[Completed]))b where ID=1) a ");
for (int j = 1; j < dic.Count; j++)
{
strSQL.Append("FULL JOIN (SELECT ID, Column1, Column2 FROM[dbo].[20200618] UNPIVOT(Column1 for Column2 in ([Annual],[Revenue],[Completed])) " + dic[j] + " where ID = " + (j+1)+ ") " + dic[j] + " on a.Column2 = " + dic[j]+".Column2 ");
}
// SqlHelper.ExcuteNoQuery(strSQL.ToString());
SQL Query Part
Data in my azure sqlserver.
When run SELECT *FROM [dbo].[20200618]
.
Run SELECT ID,Column1,Column2 FROM [dbo].[20200618] UNPIVOT(Column1 for Column2 in ([Annual],[Revenue],[Completed]))b where ID=2
.
Finally, run the code.
select isnull(a.Column2,b.Column2) Column0,isnull(a.Column1,0) Column1,isnull(b.Column1,0) Column2,isnull(c.Column1,0) Column3 from (SELECT ID,Column1,Column2 FROM [dbo].[20200618] UNPIVOT(Column1 for Column2 in ([Annual],[Revenue],[Completed]))b where ID=1) a FULL JOIN (SELECT ID,Column1,Column2 FROM [dbo].[20200618] UNPIVOT(Column1 for Column2 in ([Annual],[Revenue],[Completed]))b where ID=2) b on a.Column2=b.Column2 FULL JOIN (SELECT ID,Column1,Column2 FROM [dbo].[20200618] UNPIVOT(Column1 for Column2 in ([Annual],[Revenue],[Completed]))b where ID=3) c on a.Column2=c.Column2