How to stack two columns into rows in a single column? - sql

I have following table named 'model', I want sql server code to achieve the result.
My desired output should be as follows,
Any help would be appreciated.

You can try this - just another simple way :)
SELECT ModelA, Discount
from table1
UNION
SELECT ModelB, Discount
from table1

I like to use apply for this purpose:
select v.model, t.discount
from t cross apply
(values (model1), (model2)) v(model);
apply is a very powerful construct that implements something called "lateral joins". There are other methods to unpivot such data, but I unpivoting is a good introduction to lateral joins.

It's UNION ALL that you need:
select modela as model, discount from model
union all
select modelb, discount from model

Related

Unpivot SQL Table with multiple columns

I would like to unpivot a SQL table around multiple columns.
I have tried a normal UNPIVOT statement but that only ppivots around one value.
See this link for example: https://codingsight.com/understanding-pivot-unpivot-and-reverse-pivot-statements.
I have tried to illustrate my data as well as my desired outcome in the picture below.
The top table is a sample of the data in the SQL table. I have used 3 materials but in reality there are 20.
The bottom table is my desired outcome.
The data is on a SQL 2008-r2 server.
Any pointers on how to go about this task?
Consider using cross apply, like so:
select t.date, t.product, x.*
from mytable t
cross apply (values
(container1material, container1amount),
(container2material, container2amount),
(container3material, container3amount)
) x(material, amount)
Use apply for unpivoting:
select t.date, t.product, v.*
from t cross apply
(values (container1amount, container1material),
(container2amount, container2material),
(container3amount, container3material)
) v(containeramount, containermaterial);
unpivot is bespoke syntax (not-standard) and it only does one thing. By contrast, lateral joins are very powerful and unpivoting is only one thing that you can do with them. Apply is worth learning about.

How to efficiently perform union of two queries with and without group by

I have a query that performs a union between two select statements one that uses group by and another that doesn't. The problem is I'm selecting the same columns and using the same fucntions in both select statements. It feels Im duplicating the code and I wish to know if there's a better way to write this
I've tried to use the normal union function to two select statements, but both select statements use the same functions.
Is there a way to simplify the following query without duplication?
Example:
select
sum(col1), sum(col2)....
from table
union
select sum(col1), sum(col2)...
from table
group by class
I require a table which is obtained by combining the result of the above.
The second query may have multiple categories and first query yields only one aggregated row
The objective is to compare the income and other details of the total population with one or more of categories within the population
Thanks in advance :)
You can add the WITH ROLLUP clause to your GROUP BY and it will add an aggregate row to the end of your output i.e.
SELECT SUM(col1), SUM(col2)...
FROM table
GROUP BY class WITH ROLLUP
You have not provided the sample data to check, but one approach can be using CASE WHEN in GROUP BY.
Following UNION
SELECT Sum(col1)
FROM tablename
WHERE id <> 1
UNION
SELECT Sum(col1)
FROM tablename
WHERE id = 1
GROUP BY class
Can be written as following using CASE
SELECT Sum(col1)
FROM tablename
GROUP BY CASE
WHEN id = 1 THEN 0
ELSE 1
END

Use distinct keyword with two tables

I want to take unique values using DISTINCT keyword. I have two more tables.
Table Names:
(T1)Cand_details
Locationofwork
(T2)requirement_details
Locationofposting
I want to select these two table values by using keyword distinct. Is this possible?
select LocationOfWork
from cand_details
union
select Locationofposting
from requirement_details;
A UNION operator serves to combine data from multiple SELECT statements.
In this case, without the ALL keyword (UNION ALL), the UNION operator includes a DISTINCT function which will give you the unique locations across both tables.
Something like this?
SELECT DISTINCT Locationofwork, Locationofposting FROM Cand_details, Locationofposting
You should relate both tables with common fields if they have.
Select Locationofwork as "LOC"
From Cand_details
UNION Select Locationofposting as "LOC"
FROM requirement_details
Yes this is easily possible. You can encapsulate as many feilds as you like in the distinct ( ) clause.

SQL complex unions

This is a little tricky to describe, but hopefully there is a solution.
I have a UDF which takes an ID and returns a table. Is there a way I can do a SELECT for these IDs and perform a UNION of the UDF results? For example;
To get the IDs;
SELECT [ID]
FROM [TableOfIDs]
To get the object properties from an ID;
SELECT *
FROM GetObjectProperties(#ID)
But how do I combine the two? That is, to do a union of the UDF results from a query for the IDs?
I hope that makes sense!
You need to use APPLY:
SELECT TT.*
FROM [TableOfIDs] AS T CROSS APPLY GetObjectProperties(T.ID) AS TT;

The used SELECT statements have a different number of columns

For examples I don't know how many rows in each table are and I try to do like this:
SELECT * FROM members
UNION
SELECT * FROM inventory
What can I put to the second SELECT instead of * to remove this error without adding NULL's?
Put the columns names explicitly rather than *, and make sure the number of columns and data types match for the same column in each select.
Update:
I really don't think you want to be UNIONing those tables, based on the tables names. They don't seem to contain related data. If you post your schema and describe what you are trying to achieve it is likely we can provide better help.
you could do
SELECT *
from members
UNION
SELECT inventory.*, 'dummy1' AS membersCol1, 'dummy2' AS membersCol2
from inventory;
Where membersCol1, membersCol12, etc... are the names of columns from members that are not in inventory. That way both queries in the union will have the same columns (Assuming that all the columns in inventory are the same as in members which seems very strange to me... but hey, it's your schema).
UPDATE:
As HLGEM pointed out, this will only work if inventory has columns with the same names as members, and in the same order. Naming all the columns explicitly is the best idea, but since I don't know the names I can't exactly do that. If I did, it might look something like this:
SELECT id, name, member_role, member_type
from members
UNION
SELECT id, name, '(dummy for union)' AS member_role, '(dummy for union)' AS member_type
from inventory;
I don't like using NULL for dummy values because then it's not always clear which part of the union a record came from - using 'dummy' makes it clear that the record is from the part of the union that didn't have that record (though sometimes this might not matter). The very idea of unioning these two tables seems very strange to me because I very much doubt they'd have more than 1 or 2 columns with the same name, but you asked the question in such a way that I imagine in your scenario this somehow makes sense.
Are you sure you don't want a join instead? It is unlikely that UNOIN will give you what you want given the table names.
Try this
(SELECT * FROM members) ;
(SELECT * FROM inventory);
Just add semicolons after both the select statements and don't use union or anything else. This solved my error.
I don't know how many rows in each table
Are you sure this isn't what you want?
SELECT 'members' AS TableName, Count(*) AS Cnt FROM members
UNION ALL
SELECT 'inventory', Count(*) FROM inventory
Each SELECT statement within the MySQL UNION ALL operator must have the same number of fields in the result sets with similar data types
Visit https://www.techonthenet.com/mysql/union_all.php