T-SQL using how to use PIVOT function - sql

I have the following table structure in SQL (using T-SQL):
sqlfiddle: http://sqlfiddle.com/#!6/e5edc/1/0
The data would look something like this:
Now I would like to transpose the structure so I get the following:
columns [01_amount] to [12_amount] and columns [01_active] to [12_active] as rows instead of columns
All rows of [initials] to be separate columns
Should look like this:
How would I go about this? The Pivot function looks rather complicated as I'm new to SQL. Can someone help me in the right direction? :-)

Ok you will need first to unpivot your data, which is done in cte. Then you will need to pivot again:
;with cte as(select initials, v, col from main
unpivot(v for col in([01_amount], [02_amount])) u)
select * from cte
pivot(max(v) for initials in([rw],[nb]))p
In unpivot part just add all 24 column names for amounts and active bits. In pivot part just add all possible values for initials.
But if you don't want to manually list all possible values for initials then you will need to make some dynamic query with unpivoting and pivoting.
Here is demo for 2 columns and you will easily expand it http://sqlfiddle.com/#!6/4cf36/2

Related

Split and Concat Unique SQL comma separated values in column, and then group by

I am trying to write a SQL query that helps me find out the unique amount of "Numbers" that show up in a specific column. Example, in a select * query, the column I want can look like this
Num_Option
9000
9001
9000,9001,9002
8080
8080,8000,8553
I then have another field of "date_available" which is a date/time.
Basically, what want is something where I can group by the "date_available" while combing all the Num_Options on that date, so something like this..
Num_Option date_available
9000,9001,9002,8080 10/22/2020
9000,9002,8080,8000,8553 10/23/2020
I am struggling to figure this out. I have gotten to the possible point of using a python script and matplotlib instead... but I am hoping there is a SQL way of handling this as well.
In Postgres, you can use regexp_split_to_table() in a lateral join to turn the csv elements to rows, then string_agg() to aggregate by date:
select string_agg(x.num, ',') num_option, t.date_available
from mytable t
cross join lateral regexp_split_to_table(t.num_option, ',') x(num)
group by date_available
Of course, this assumes that you want to avoid duplicate nums on the same data (otherwise, there is not need to split, you can directly aggregate).
You may just be able to use string_agg():
select date_available, string_agg(num_option, ',')
from t
group by date_available;
first you have to split the strings into multiple rows with something like split_part('9000,9001,9002',',',1) etc. (use UNION ALL to append the 2nd number etc.), then group them back by availability date with string_agg
if you don't want to hardcode split_part part there is an answer here on how to dynamically split strings in Redshift, look for it

SQL Pivot: Can I make the pivot list dynamic without using stored proc?

Here is my SQL containing a pivot:
select * from (
select
[event_id]
,[attnum]
,PollId
,PollResponseDisplayText
from
[dbo].[v_PollReportDetails2]
) as tmp
pivot (max(tmp.[PollResponseDisplayText])
for tmp.PollId in ([703],[805],[806],[807],[808],[809])) as pivot_table
I want to change the pivot list to be something like this:
for tmp.PollId in (select PollId
from Polls
where event_id = 100100
and isVisible = 1)) as pivot_table
I can do this all in a stored proc and dynamically generate a SQL statement to feed into an execute() statement, but I need to be able to do this in a view.
Maybe I'm looking in the wrong places, but I can't seem to find official documentation that actually says that this can't be done. But after hours of experimenting and discussions, Apparently, this can not be done this way.
#aeoluseros said it best in his comment,
syntax of PIVOT clause requires these distinct values to be known at
query design time. So you cannot use that in view
Logically, this would make sense, because as we add rows to the table over time, it would have the potential to add columns dynamically to the view result.
Thanks #Damien_The_Unbeliever for additional clarification, see here:
https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15#syntax

Dax How to get distinct values from a column

This is the query I'm trying.
EVALUATE
SELECTCOLUMNS('MyTable',"col1",DISTINCT(VALUES('MyTable'[Email])))
If you are trying to simply create a new, single column table with the distinct values of an existing table, you can use the formula below.
Starting with data like this...
... simply create a new table with this formula to get a list of distinct values.
Locations = DISTINCT(Fruit[Location])
This will work:
Evaluate
VALUES('Table'[Column])

Is it possible to avoid specifying a column list in a SQL Server CTE?

Is it possible to avoid specifying a column list in a SQL Server CTE?
I'd like to create a CTE from a table that has many columns so that the structure is identical. There probably is a way to accomplish this without relisting every column name.
I've tried (unsuccessfully):
with pay_cte as
(select * from payments)
select * from pay_cte
I'm encouraged in my quest by this statement in the msdn documentation:
The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.
https://msdn.microsoft.com/en-us/library/ms175972.aspx
Yes, assuming you mean that you don't have to name every column in the with cte(Col1, Col2) as section.
You can easily try this yourself with a very simple test query along the lines of:
with cte as
(
select *
from sys.tables
)
select *
from cte

Unpivot columns from another table [duplicate]

This question already has an answer here:
unpivot with dynamic columns plus column names
(1 answer)
Closed 8 years ago.
I have used Unpivot to get data from a table I am trying to manipulate. I use this query to rearrange my columns to rows;
SELECT Id, ownername, ownervalue
FROM Contacts UNPIVOT (ownervalue FOR ownername IN (column1, column2, column3)) unpiv;
This works great. However I would prefer to get my column names from another table instead of hard-coding them in the query. Ideally i would like this, but it does not work;
SELECT Id, ownername, ownervalue
FROM Contacts UNPIVOT (ownervalue FOR ownername IN (SELECT * FROM ColumnsTable)) unpiv;
Is it possible to get my list of columns from another table like this?
As far as I know (please correct me if I'm wrong) it is not possible to use dynamic columnnames without the use of a dynamic query, which is executed with for example exec.
Take a look at the following question unpivot with dynamic columns plus column names