SQL to transpose table - sql

Looking for a simple way to kind-of transpose a table to be able to further analyze data in software with no DB capabilities.
Table:
Id testdate partid testid
1 2-13-2014 45 58
2 2-23-2014 45 2
I want to extract a table from this that puts testid in the column name and date in its fields, thus looks like this:
partid test-1 test-2 test-3 ... test-58 ...
45 2-23-2014 2-13-2014
There could be a few 100 testid's. I plan to expand the code to multiple columns per testid, eg: test-1-date test-1-result test-1-success.
Prefer common SQL, but if it has to be specific I'd be MS SQL server.

Okay, found it, its "PIVOT" that I needed. When searching PIVOT there are many questions and answers on this site.
One thing that is different in my case compared with most other PIVOT examples is that I try to aggregate strings rather than numbers. (Think of the date field as a string)
Specifically helpful were:
How to create a pivot query in sql server without aggregate function
Get ROWS as COLUMNS (SQL Server dynamic PIVOT query)
Convert Rows to columns using 'Pivot' in mssql when columns are string data type
Pivot table strings grouping under pivot column?

Related

Pivot a Table in PostgreSQL with Many Keys [duplicate]

This question already exists:
how to write ```crosstab``` in postgres with many keys (too many to write out) [closed]
Closed 2 years ago.
I am pivoting a table of the form id, key, value where there are many types of keys (130). There are too many keys to explicitly enumerate the types in the crosstab() call, or write out the crosstab_N function definition as recommended in the crosstab documentation:
row_name TEXT,
category_1 TEXT,
category_2 TEXT,
.
.
.
category_N TEXT
);
How do I pivot this table into wide format with columns id, category_1, category_2, ... category_130? I find it hard to believe you can't pivot such tables in SQL without explicitly enumerating the column types. For example in R, using the tidyverse package I would just call dataframe %>% spread(key=key, value=value)
I find it hard to believe you can't pivot such tables in SQL without explicitly enumerating the column types.
A SQL query returns a fixed set of columns. SQL is a descriptive language, and you need to tell the database which columns you want in the resultset so it can understand your requirement, and build the proper query plan.
Typical solutions involve dynamic SQL: that is, use a query to generate the actual query string, then execute it. That's an additional level of indirection, that is can be somehow challenging.
One half-way solution is JSON. If you can live with a result where all key/pair values are aggregated in a single column a JSON object, you can do:
select id, json_object_agg(key, value) obj
from mytable
group by id

How can I separate column values in to column names?

Im trying to make a table with dynamic columns.
I have this table. This is just simplified, in other instances these may have more values instead of 3.
name
----------------------
Fall
Medication
Wander
(3 rows)
I am trying to get this result. I need to separate the values into columns.
Fall | Medication | Wander
--------+------------+--------
(0 rows)
You need to PIVOT the table. Unfortunately MySQL (unlike Oracle http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html) doesn't have a PIVOT operator, but there are workarounds it seems. MySQL pivot table
You might try one of the crosstab() functions in newer PostgreSQL. See https://www.postgresql.org/docs/current/static/tablefunc.html (F.35.1.2 and F.35.1.4). It allowes you to specify a query that has row-names (those create rows), categories (that create columns) and values (that populate the inside part of the table.
The variant with 2 queries can be especially useful since it allows you to specify the columns you want to use with a seperate query.

SQL Server : Querying Multiple Rows, Returning In One

Problem
We are currently working with some data which is stored as in the screenshot below. We are using this to display information in a C# application. The only way we can get the application to work as needed is to have the information in one single row.
We have tried some methods on Display multiple rows and column values into a single row, multiple column values to no avail.
Desired output
We require each row with the same date and vehicleID to be on the same row to be output from our stored procedure.
Any help would be greatly appreciated. Cheers.
if I understood correctly, you don't know how many unique date/vehicle_id combinations there are in the data. hence you can't just do a pivot over a set list of values.
in this case, you would need to build up a list of the date/vehicle ids dynamically, and then pivot over that list.
please check out the following examples involving dynamic SQL and pivot tables:
PIVOT in sql 2005
SQL Server : dynamic pivot over 5 columns
Pivot Dynamic Columns, no Aggregation
https://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server-2005/
SQL Server dynamic PIVOT query?
Dynamic Pivot Columns in SQL Server
SQL Pivot Query with Dynamic Columns

Retrieving a unique dataset from XML fields in SQL 2008 R2

I currently have several rows (say around 100 for args sake) in a table, and within that table I have an XML field which contains data as follows (example):
<cf1>summer</cf1>
.. I might then have another row or rows containing:
<cf1>winter</cf1>
.. and for completeness, another few rows perhaps containing multiples of:
<cf1>spring</cf1>
So my question is:
How to write a query/proc to return me a unique resultset of all possible xml nodes in my xml field?
I guess I can return say 100 rows, and then using C# to filter that down.. but I am guessing that with SQL 2008 there are far better ways of doing that!
The idea is that you use XQuery to grab the data in a subquery and just treat it as another row in the table. Like such:
SELECT DISTINCT Season
FROM
(SELECT CAST(Xml_Field.query('data(/cf1)') AS VARCHAR) AS Season
FROM My_Xml_Table)
This query will return:
Season
------
summer
winter
spring

How can I return multiple rows as a single row in T-SQL?

A few months ago our vendor added a capability to our ticketing system which lets us add any number of custom fields to a ticket. I'd like to query these fields out along with the other call information for reporting purposes, but each extensible field is stored as a row in the database. So basically you have something like this:
ext_doc_no call_record value
1 1001 Test
2 1001 test2
3 1001 moretest
What I'd like is to query back:
1001 Test test2 moretest
I've tried to use PIVOT, but that's rather demanding about things like using an aggregate function. Any other ideas on how to do this?
EDIT: I also tried querying each row separately into the main query, and using a function... but both methods are way too slow. I need something to get all the rows at once, PIVOT them and then join into the main query.
Try to look at this answer.
It does exactly what you want to do.
See here Concatenate Values From Multiple Rows Into One Column Ordered SQL 2005+
or for a 2000 version Concatenate Values From Multiple Rows Into One Column
What you want to do is a pivot (some systems call it a crosstab query). That should help you google for additional help, but generally you need to know what columns you expect before writing the query.
return data as XML
SELECT ...
FROM ...
...JOIN....
FOR XML AUTO
http://www.sqlservercentral.com/scripts/Miscellaneous/32004/
Using the script from above page.
DECLARE #Values VARCHAR(1000)
SELECT #Values = COALESCE(#Values + ', ', '') + Value
FROM .....
WHERE ....
SELECT #ValuesEND
EDIT: I don't want to be rude. But you could find this by searching "combining multiple rows into one".