Here's a solution that eliminates empty columns AND keeps the order of the columns. As table is often used to define the order of fields, keeping it is essential. Tested about a dozen possibilities and the only generic one I found (where you don't have to know the column names) is using transpose, which eliminates empty columns when creating rows of it:
`| makeresults count=3
| rename comment as "generate some test data"
| streamstats count
| eval f2=if(count=2,"YYY",null), f3=if(count=3,"ZZZ",""),f5="XXX",f6=null
| rename comment as "f1, f4 and f6 have no values in any row"
| table f6 f5 f4 f3 f1 f2 count
| rename comment as "now the transpose magic"
| transpose
| transpose header_field=column
| fields - column`
... View more