Specific Pivot Query - sql

I have been looking at pivoting columns and would be grateful of any help. I see plenty of examples for summing a row on the pivot but I have a different scenario. I have a field that is JSON which is parsed and the output gets placed in a view as so.
ID Name StringValue
1 type user
1 name aeolos smith
1 access admin
2 type user
2 name ramuh smith
2 access author
I would like to Pivot this somehow to end up like the following.
type name access
user aeolos smith admin
user ramuh smith author
and so on for any entries with the identifier being the ID.
Is this possible?

You did not specify what database you are using, but it your database supports windowing functions like row_number() then you can use an aggregate function with a CASE expression along with the row number to get the final result:
select
max(case when name = 'type' then stringvalue end) type,
max(case when name = 'name' then stringvalue end) name,
max(case when name = 'access' then stringvalue end) access
from
(
select id, name, stringvalue,
row_number() over(partition by name order by id) seq
from yourtable
) d
group by seq;
See SQL Fiddle with Demo
If your database supports the PIVOT function, then you will still use the row_number() windowing function along with pivot to get the final result:
select type, name, access
from
(
select name nm, stringvalue,
row_number() over(partition by name order by id) seq
from yourtable
) d
pivot
(
max(stringvalue)
for nm in (type, name, access)
) piv;
See SQL Fiddle with Demo

Related

I need first 2 occurrences of duplicate id in the output(image attached) using sql

want first 2 occurrence of duplicate ID'S in the output, desired output in image attached.
Please help
I'm not sure what you meant by "1st occurrence" because sql select queries are unorder unless you specified the order. So I'm assuming you are using alphabetical ordering on the emails.
SELECT t.id, t.email, t.state_code FROM (
SELECT id, email, state_code,
ROW_NUMBER() OVER(partition by id ORDER BY email desc) as cnt
FROM testdb
group by id, email, state_code
) as t
WHERE t.cnt <= 2
db fiddle link

SQL query looping for each value in a list

New to SQL here - I am trying to get 1 row from a table matching to a particular criteria
Typically this would look like
SELECT TOP 1 *
FROM myTable
WHERE id = 'abc'
The output may look like
value id
--------------
1 abc
The table has many entries for an 'id', and I am trying to get one entry per 'id'. Now I have list of 'id's. How would I execute something like
SELECT TOP 1 *
FROM myTable
FOR EACH id
WHERE id IN ('abc', 'edf', 'fgh')
Expecting result like
value id
--------------
1 abc
10 edf
12 fgh
I do not know if it is some sort union or concat operation, but would like to learn. I am working on Azure SQL Server
The table has many entries for an 'id', and I am trying to get one entry per 'id'. Now I have list of 'id's.
A typical method is row_number():
select t.*
from (select t.*,
row_number() over (partition by id order by id) as seqnum
from mytable t
) t
where seqnum = 1;
Note: you can filter on particular ids, if you want. It is unclear if that is really required for your question.
If you happen to be using SQL Server (as select top suggests), you can use the more concise, but somewhat less performant:
select top (1) with ties t.*
from mytable t
order by row_number() over (order by id order by (select null));

SQL command to get highscore position with similar scores

Please guide me to write an optimize sql command to get real position(ranking) of the users by id order with similar scores.
I have written below Select Command but it can't distinguish names with similar scores and if i use "AND" to specify the gamer's name it only shows number 1 as row number that is not what i want !
Fields : id , name , score
SELECT COUNT(id) AS Num
FROM Hscore
WHERE (score>= #scorenumber)
Thanks
I think this is the query you're looking for:
SELECT
[RANK]
, ID
, NAME
, SCORE
FROM (
SELECT
DENSE_RANK() OVER (ORDER BY ID DESC) [RANK]
, ID
, NAME
, SCORE
FROM Hscore
WHERE (score>=#scorenumber)
) ResultSet
WHERE Name = 'Milad'
ORDER BY SCORE DESC
I'm assuming you're using SQL Server, since you're using the standard notation for a variable, with a # before the variable name.

SQL Server : Getting distinct count on every column in a large view

I have a large SQL Server 2012 database with a couple of views I need to analyse.
What I want to know for each view is the number of unique values of each column in the view. I could not find any script yet that would give me this.
So the input should be the view name and the output would be two rows like:
Column Uniques
accountid 200
accountname 178
numberofemp 23
telephone 154
notusedyet 0
You need to use COUNT() (an aggregate function) with Distinct to count only the unique values.
SELECT [column], COUNT(DISTINCT value) [Uniques]
FROM tableName
GROUP BY [column]
Get a distinct count for each column via count(distinct [ColA]) for each column you want to count (no group by). You can then unpivot to get the tabular format you desire. Here's an example:
;with DistinctColumnCount( Id, Description )
as
(
select
count(distinct Id) Id
, count(distinct Description) Description
from
EntityB
)
SELECT CountColumn, [Count].[DistinctCount]
FROM
DistinctColumnCount
unpivot
( DistinctCount for CountColumn in ( Id, [Description] ) ) as [Count]

Distinct SQL Query

I have a SQL Server 2008 database with the following information in a table:
ID Name
-- ----
1 John
2 Jill
3 John
4 Phil
5 Matt
6 Jill
I want to display the unique names in a drop down list. Because of this, I need just one of the IDs associated with the unique name. I know it's dirty. I didn't create this mess. I just need the unique names with one of the ids. How do I write a query that will do that? I know that the following won't work because of the ID field.
SELECT DISTINCT
[ID], [Name]
FROM
MyTable
SELECT MIN(ID) AS ID, [Name]
FROM MyTable
GROUP BY [Name]
This will return the first (i.e. MINimum) ID for each distinct Name
You could also do it with rank over function
SELECT
Id,
Name
FROM
(
SELECT
Id,
[Name],
RANK() OVER (PARTITION BY [Name] Order By Id) As Idx
FROM Test
) A
WHERE Idx = 1
To get understanding about rank over function read this:
http://msdn.microsoft.com/en-us/library/ms176102.aspx