How to add a variable to auto pickup column row names and turn it into new column headers using Pivot query in Oracle Sql developer - pivot-table

Initial table students
NAME School Class
John Hs English
Steve Hs Maths
Matthew Hs Science
Jim Hs History
Output Needed: I need the query to auto pick up Name column data from initial table and change it to column headers in output and since the names will continuously change i cannot hard code the names using simple pivot query. I am new to pivot queries so I wanted to request if someone can help me out. Thank You.
School John Steve Matthew Jim
Hs English Maths Science History
Here's what i tried: *Note( I am trying to use this query in Oracle Sql Developer to achieve the output format)
declare
sqlqry clob;
cols clob;
begin
select listagg('''' || NAME || ''' as "' || NAME || '"', ',') within group (order by NAME)
into cols
from (select distinct NAME from Students);
sqlqry :=
'
select * from(select NAME,SCHOOL,CLASS from Students)
pivot(MAX(CLASS) FOR NAME IN (' || cols || ')
)';
execute immediate sqlqry;
end;

Related

SQL Server 2008 - insert into column from 2 different tables

I am wondering how I would have a single column, for example called ClientID, I want to be able to select from two different tables and have all the results go into this column.
This is what I am currently trying but I am getting errors:
SELECT ClientID = ('basic' + CAST(a.BasicCID as VARCHAR(15))) AND =('premium' + CAST(c.PremiumCID as VARCHAR(15)))
I want the output to display something like this
ClientID Name
------- --------
basic1 John
basic2 Pat
premium1 Mary
premium2 Sean
Okay, You can do something like this -
Insert into YourTable(ClientID, Name)
SELECT 'basic' + CAST(a.BasicCID as VARCHAR(15)), Name From BasicTable a
UNION
SELECT 'premium' + CAST(c.PremiumCID as VARCHAR(15)), Name From PremiumTable c

Creating custom order by SQL Server

Customer wants to display a list of values returned by my query in a specific order. The issue is ordering simply by asc or desc is not giving me what the customer want. DBA doesn't want me to hard code values. Is there a way to custom sort without hard coding values? Because the values will change every year and would have to maintain/update it every year.
Table Structure:
Column: CMN_CodesID (unique), Name (is what I'd like to display in custom order)
something like this.
order by case when Jack then 1
when Apple then 2
when Orange then 3
...
End
You could use dynamic sql in a stored procedure and pass #MyOrderBy into it as a parameter (Added to this example for illustration).
DECLARE #MyOrderBy VARCHAR(300)
SELECT #MyOrderBy = 'case when myfield = ''Jack'' then 1 when myfield = ''Apple'' then 2 when myfield = ''Orange'' then 3 else 4 End'
DECLARE #sSQL VARCHAR(300)
SELECT #sSQL = 'SELECT * FROM mytable ORDER BY ' + #MyOrderBy
EXEC(#sSQL)

SQL Server 2008 ssrs multiple records into one

I've been reading other similar "multiple records into one" posts, but either cannot seem to get any to work, or they don't really apply to what I am trying to do.
Here are my 3 tables. vehicle, vehicle_repair, comments
vehicle columns: vehicle_name and other vehicle related info,vehicle_make, vehicle_model
vehicle_repair columns: vehicle_name, vehicle_repair_type, vehicle_repair_num, etc, etc
comments columns: vehicle_name,vehicle_repair_num, comments_detail
The way the program is written, if I write more than 1 line of comments, it doesn't concatenate them, it makes 1 entry for each line, ie:
comments table:
vehicle_name vehicle_rpr_num comments_detail
--------------------------------------------------------------------
150 1 replaced hose
750 1 replaced belt
750 2 replaced fuel and also saw that the
750 2 timing belt needs to be replaced
750 2 as well
I was trying to use something like:
select
substring((select ' '+comments_detail AS 'data()'
from comments
for xml path('')), 3, 80) as 'comments_detail'
from
comments
I tried to add the join and other tables inside the substring but then the comments_details become all jacked up, like it then combines 20 comments together instead of 1 at a time.
I'd rather start from scratch and see if I can get it working another way.
My issue comes in when I try to link the 3 tables above.
I do not know how to put in the other fields that I need from the vehicle table, ie vehicle_make, vehicle_model
Any ideas? Am I writing my concatenate completely wrong? I am trying to put this into a stored procedure, would a view be better?
SELECT c1.vehicle_name,
c1.vehicle_rpr_num,
STUFF((SELECT ' ' + comments_detail
FROM comments c2
WHERE c2.vehicle_name = c1.vehicle_name
AND c2.vehicle_rpr_num = c1.vehicle_rpr_num
FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),
1,1,'')
AS comments
FROM comments c1
GROUP BY c1.vehicle_name, c1.vehicle_rpr_num;
SQLFiddle with the sample comments data.
You were on the right track using FOR XML PATH to concatenate the comments. There are many different ways to concatenate, a good article on the pros/cons of each is here. I'd put this into a view definition to allow for easier joining with other tables.
CREATE TABLE tbl (vehicle_name INT,vehicle_rpr_num INT,comments_detail NVARCHAR(1000))
INSERT INTO tbl
VALUES
(150,1,'replaced hose'),
(750,1,'replaced belt'),
(750,2,'replaced fuel and also saw that the'),
(750,2,'timing belt needs to be replaced'),
(750,2,'as well')
SELECT DISTINCT t.vehicle_name, t.vehicle_rpr_num , STUFF(List.Comments, 1 ,2, '') AS Comments
FROM tbl t
CROSS APPLY (
SELECT ' ' + comments_detail [text()]
FROM tbl
WHERE vehicle_name = t.vehicle_name
AND vehicle_rpr_num = t.vehicle_rpr_num
FOR XML PATH('')
)List(Comments)
Result Set
vehicle_name vehicle_rpr_num Comments
150 1 eplaced hose
750 1 eplaced belt
750 2 eplaced fuel and also saw that the timing belt needs to be replaced as well

LIKE function in SQL Server 2008 suggestion needed

I have a table Customer with 2 columns Name and Surname (sql Server 2008). User wants to search by Name-Surname - or just typing Jo Bloggs. Suppose a row is filled with
CustomerId Name Surname
1 Jo Bloggs
doing
select * from customer where Name like '%Jo%' will find the records
select * from customer where Surname like '%Bloggs%' will find the records
But How can I make it return records for if user types both Name and Surname eg Jo Bloggs?
You could also create a computed column and search on that:
ALTER TABLE dbo.customer
ADD FullName as Name + ' ' + Surname PERSISTED
Now you'd have an extra column FullName in your customer table, which is always up to date, and you can search for:
SELECT (list of fields) FROM dbo.customer
WHERE Fullname = 'Jo Bloggs'
and since it's a persisted, computed column, you can even put an index on it to make exact searches faster
This should work whether user enters First Name, Surname or both.
SELECT *
FROM customer cus
WHERE ((cus.Name like #FirstName) OR (#FirstName IS NULL)) AND
((cus.Surname like #Surname) OR (#Surname IS NULL))
I used two variables because entering input values into an SQL string is strongly discouraged, as it exposes to SQL Injection (other than being slower).
select * from customer where Name like '%Jo%' and Surname like '%Bloggs%'
select * from customer where Name like '%Jo%'
union
select * from customer where Surname like '%Bloggs%'

How do i find the total number of records created on a given day using T-SQL?

I need to find out the total number of records that were created on a given day.
e.g.
ID CreatedDate
1 17/07/2009
2 12/07/2009
3 17/07/2009
4 05/07/2009
5 12/07/2009
6 17/07/2009
Output:
3 Records were created on 17/07/2009
2 Records were created on 12/07/2009
1 Record was created on 05/07/2009
EDIT
Upon testing the second suggestion made by Chris Roberts of including the formatting in the SQL i get this error:
Syntax error converting the varchar value ' Records were created on ' to a column of data type int.
Does anyone know how to rework the solution so that it works?
You should be able to get the data you're after with the following SQL...
SELECT COUNT(ID), CreatedDate
FROM MyTable
GROUP BY CreatedDate
Or - if you want to do the formatting in the SQL, too...
SELECT CONVERT(varchar, COUNT(ID)) + ' Records were created on ' + CONVERT(varchar, CreatedDate)
FROM MyTable
GROUP BY CreatedDate
Good luck!
Is the column actually a timestamp? In which case you will need to apply a function to remove the time component, e.g.:
SELECT COUNT(*), date(CreatedDate) FROM MyTable GROUP BY date(CreatedDate)
I don't know what the function is in T-SQL, it's date() in MySQL and trunc() in Oracle. You may even have to do a to_string and remove the end of the string and group by that if you lack this.
Hope this helps.
select count(*), CreatedDate from table group by CreatedDate order by count(*) DESC

Resources