rows to columns based on first column - sql

I have a student table like below
name | subject | scode
sam | science | 20
sam | computer | 30
sam | language | 50
sam | history | 20
joe | PET | 30
joe | computer | 50
dan | lab | 40
i am looking for out put like below
name | 20 | 30 | 40 | 50
sam | science | computer | null | language
sam | history | null | null | null
joe | null | PET | null | Computer
dan | null | null | lab | null
there are chances a student can add one more subject in future and code is dynamic for that particular student
i tried using for xml however able to get in the format of xml but not able to transpose it. any help in pivoting this as per the output is possible?

I think pivoting in combination with dynamix SQL qould do the trick. I created an approach for this, but this will require some more modification: currently it would group away the second line with scode 20 for student sam. Give it a try - when you get stuck, I will try to modify it a little more:
IF OBJECT_ID('dbo.tbl_test') IS NOT NULL
DROP TABLE tbl_test
GO
CREATE TABLE tbl_test (
sName varchar(25)
,sSubject varchar(25)
,sCode int
)
GO
INSERT INTO tbl_test VALUES
('sam', 'science', 20)
,('sam', 'computer', 30)
,('sam', 'language', 50)
,('sam', 'history', 20)
,('joe', 'PET', 30)
,('joe', 'computer', 50)
,('dan', 'lab', 40)
DECLARE #Cols NVARCHAR(MAX);
DECLARE #Qry NVARCHAR(MAX);
SELECT #Cols = STUFF((SELECT DISTINCT ', [' + CAST(scode AS VARCHAR(5)) + ']'
FROM tbl_test
ORDER BY 1
FOR XML PATH ('')), 1, 1, '')
SET #Qry = 'WITH cte AS(
SELECT sName_GRP, sName, ' + #Cols + '
FROM (
SELECT sName, sCode, sSubject, sName + ' + CHAR(39) + '_' + CHAR(39) + ' + RIGHT(' + char(39) + '0000' + CHAR(39) +' + CAST(ROW_NUMBER() OVER (PARTITION BY sName, sCode ORDER BY sName, sCode) AS VARCHAR(5)), 5) sName_GRP
FROM tbl_test
) AS j
PIVOT
(
MAX(sSubject) FOR sCode in (' + #Cols + ')
) AS p
)
SELECT sName, ' + #Cols + '
FROM cte'
EXEC sp_executesql #Qry

Related

How do I include an additional non-aggregated column for each of my in my PIVOT values?

I have the following code fragment which gives me the current results below. I'm attempting to add an additional column for each of my pivoted values in order to include the lastview data for each of my siteuserid / tagname combo (see expected results). Since this column isn't an aggregation, I don't believe an additional pivot would help. I've tried multiple ways of adding lastview, but it always results in additional rows rather than the desired output.
create table #taghits (userid int, email varchar(20), tagname varchar(20), hits int, lastview date)
insert into #taghits select 1, 'email1#here.com', 'tag1', 3, '2020-03-24';
insert into #taghits select 2, 'email2#here.com', 'tag1', 1, '2020-03-17';
insert into #taghits select 2, 'email2#here.com', 'tag2', 1, '2020-03-18';
insert into #taghits select 3, 'email3#here.com', 'tag1', 2, '2020-03-25';
insert into #taghits select 3, 'email3#here.com', 'tag2', 5, '2020-03-28';
select * from #taghits;
DECLARE #Columns3 as NVARCHAR(MAX)
SELECT #Columns3 = ISNULL(#Columns3 + ', ','') + QUOTENAME(TagName)
FROM (
select distinct TagName
from #taghits
) AS TagNames
ORDER BY TagNames.TagName
DECLARE #scolumns as NVARCHAR(MAX)
SELECT #scolumns = ISNULL(#Scolumns + ', ','')+ 'ISNULL(' + QUOTENAME(TagName) + ', 0) AS '+ QUOTENAME(TagName)
FROM (select distinct TagName
from #taghits) AS TagNames
ORDER BY TagNames.TagName
DECLARE #SQL as NVARCHAR(MAX)
SET #SQL = '
select userid, email, ' + #scolumns + '
from
(
select userid, email, tagname, hits
from #taghits
) as TagHits
PIVOT (
SUM(hits)
FOR TagName IN (' + #Columns3 + ')
) AS PivotTable
order by userId
'
exec sp_executesql #SQL;
Current Result
| userid | email | tag1 | tag2 |
|--------|-----------------|------|------|
| 1 | email1#here.com | 3 | 0 |
| 2 | email2#here.com | 1 | 1 |
| 3 | email3#here.com | 2 | 5 |
Desired Result
| userid | email | tag1_hits | tag1_lastview | tag2_hits | tag2_lastview |
|--------|-----------------|-----------|---------------|-----------|---------------|
| 1 | email1#here.com | 3 | 2020-03-24 | 0 | null |
| 2 | email2#here.com | 1 | 2020-03-17 | 1 | 2020-03-18 |
| 3 | email3#here.com | 2 | 2020-03-25 | 5 | 2020-03-28 |
try the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((select distinct ',
SUM(CASE WHEN tagname=''' + CAST(tagname as varchar(10)) + ''' THEN [hits] ELSE 0 END) AS [' + CAST(tagname as varchar(10)) + '_hits],
MAX(CASE WHEN tagname=''' + CAST(tagname as varchar(10)) + ''' THEN [lastview] ELSE NULL END) AS [' + CAST(tagname as varchar(10)) + '_lastview]'
/*---------------You can add other columns here similar to above--------------*/
FROM #taghits
FOR XML PATH(''),type).value('.','varchar(max)'),1,2,'')
SET #query = 'SELECT userid, email, ' + #Cols + ' FROM #taghits group by userid, email'
print (#query)
exec(#query)
Please see db<>fiddle here.

How to export report and mark a column with data?

This is hard to explain but I'll try. I need to export a report that shows which stores have locations in which states.
Suppose I have the following table:
+----------+-----------+
| STORE_ID | STATE_ABV |
+----------+-----------+
| 1 | AK |
| 1 | AL |
| 1 | AR |
| 2 | MI |
| 2 | OH |
| 2 | IN |
| 3 | CA |
| 3 | NV |
+----------+-----------+
The STORE_ID column is a key to another table where I just need to pull out the STORE_NAME column.
+----------+------------+
| STORE_ID | STORE_NAME |
+----------+------------+
| 1 | Walmart |
| 2 | Target |
| 3 | Kroeger's |
+----------+------------+
What I want is to export a list of each store along with columns for all states. If the store is available in that state, I want to place an "X" for the value.
So the desired output looks like this:
+------------+----+----+----+----+----+----+----+----+
| STORE_NAME | AK | AL | AR | CA | IN | OH | MI | NV |
+------------+----+----+----+----+----+----+----+----+
| Walmart | X | X | X | | | | | |
| Target | | | | | X | X | X | |
| Kroeger's | | | | X | | | | X |
+------------+----+----+----+----+----+----+----+----+
Is this possible in SQL Server? How would I write such a query? There should be a column for every STATE_ABV that exists in the table.
As mentioned, what you are after here is to pivot your data. Personally I dislike the PIVOT functionality of SQL Server, and much more prefer using a Cross-Tab (aka conditional aggregation).
As I suspect that this is going to require a dynamic pivot, I've done that as well:
--Sample tables
CREATE TABLE dbo.StoreLocations (StoreID int,
StateAbv char(2));
CREATE TABLE dbo.Stores (StoreID int IDENTITY,
StoreName varchar(20));
GO
--Sample data
INSERT INTO dbo.Stores (StoreName)
VALUES('Walmart'),('Target'),('Kroeger''s');
INSERT INTO dbo.StoreLocations (StoreID,StateAbv)
VALUES(1,'AK'),
(1,'AL'),
(1,'AR'),
(2,'MI'),
(2,'OH'),
(2,'IN'),
(3,'CA'),
(3,'NV');
GO
--Quick sample to get the format right
SELECT S.StoreName,
IIF(COUNT(CASE WHEN SL.StateAbv = 'AK' THEN 1 END) = 0,NULL, 'X') AS AK
FROM dbo.Stores S
LEFT JOIN dbo.StoreLocations SL ON S.StoreID = SL.StoreID
GROUP BY S.StoreName;
GO
--The real solution
DECLARE #SQL nvarchar(MAX);
SET #SQL = N'SELECT S.StoreName,' + NCHAR(13) + NCHAR(10) +
STUFF((SELECT N',' + NCHAR(13) + NCHAR(10) +
N' IIF(COUNT(CASE WHEN SL.StateAbv = ' + QUOTENAME(SL.StateAbv,'''') + N' THEN 1 END) = 0, NULL,''X'') AS ' + QUOTENAME(SL.StateAbv)
FROM dbo.StoreLocations SL
GROUP BY SL.StateAbv --Could use DISTINCT too
ORDER BY SL.StateAbv
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,3,N'') + NCHAR(13) + NCHAR(10) +
N'FROM dbo.Stores S' + NCHAR(13) + NCHAR(10) +
N' LEFT JOIN dbo.StoreLocations SL ON S.StoreID = SL.StoreID' + NCHAR(13) + NCHAR(10) +
N'GROUP BY S.StoreName;';
PRINT #SQL; --Your best friend
EXEC sp_executesql #SQL;
GO
--Clean up
DROP TABLE dbo.Stores;
DROP TABLE dbo.StoreLocations;
db<>fiddle
I foolishly assumed that the state was unique in StoreLocations. Ideally, you should have a States table as well, then you don't need to get the distinct states from the StoreLocations table.
Example with a States table: db<>fiddle
Just in case you want the dynamic pivot. Personally, I don't mind PIVOT. It is just another screwdriver in the toolbox.
The UNION ALL portion can be removed if you don't mind NULL values
Example dbFiddle
Declare #SQL varchar(max) = '
Select *
From (
Select A.Store_ID
,A.State_Abv
,B.Store_Name
,Value = ''X''
From StoreLocations A
Join Stores B on A.Store_ID=B.Store_ID
Union All
Select B.Store_ID
,A.State_Abv
,B.Store_Name
,Value = ''''
From (Select Distinct State_Abv from StoreLocations) A
Cross Join Stores B
) A
Pivot (max(Value) For [State_Abv] in (' + Stuff((Select Distinct ',' + QuoteName(State_Abv) From StoreLocations Order By 1 For XML Path('')),1,1,'') + ') ) p
Order By Store_ID
'
Exec(#SQL)
Returns
Option with NULL Values
Declare #SQL varchar(max) = '
Select *
From (
Select A.Store_ID
,A.State_Abv
,B.Store_Name
,Value = ''X''
From StoreLocations A
Join Stores B on A.Store_ID=B.Store_ID
) A
Pivot (max(Value) For [State_Abv] in (' + Stuff((Select Distinct ',' + QuoteName(State_Abv) From StoreLocations Order By 1 For XML Path('')),1,1,'') + ') ) p
Order By Store_ID
'
Returns

Dynamic Pivot of Email Addresses

I have tried to research this, and I am unable to find something quite like it. I have a table that may have entries added many times over as well as deleted. I have no idea how many columns I will need, therefore I need a Dynamic Pivot. All the examples I see use a windows function, but I am pivoting email addresses.
The Table would look something like this:
Number | Email
--------------
1 | email1#email.com
1 | email2#email.com
1 | email3#email.com
2 | email4#email.com
2 | email5#email.com
3 | email6#email.com
4 | email7#email.com
4 | email8#email.com
I want the table to look like this(when all are included):
Number | Email1 | Email2 | Email3
---------------------------------------------------------------
1 | email1#email.com | email2#email.com | email3#email.com
2 | email4#email.com | email5#email.com |
3 | email6#email.com | |
4 | email7#email.com | email8#email.com |
If Number 1 wasn't included it would look like:
Number | Email1 | Email2
--------------------------------------------
2 | email4#email.com | email5#email.com
3 | email6#email.com |
4 | email7#email.com | email8#email.com
Thanks for the help!
Here is code to create a mock table:
CREATE TABLE #table
(number INT, email VARCHAR(30))
INSERT INTO #table (number, email)
VALUES (1,'email1#email.com')
,(1,'email2#email.com')
,(1,'email3#email.com')
,(2,'email4#email.com')
,(2,'email5#email.com')
,(3,'email6#email.com')
,(4,'email7#email.com')
,(4,'email8#email.com')
This is similar to what I have tried, I used count to try and just make it work, but was unable.
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N', p.' + QUOTENAME(Number)
FROM (SELECT p.Number FROM #table AS p
GROUP BY p.Name) AS x;
SELECT #columns
SET #sql = N'
SELECT ' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT p.number, p.email
FROM #test p
) AS j
PIVOT
(
Count(email) FOR Name IN ('
+ STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT #sql;
EXEC sp_executesql #sql;
You first need to create a RNO by partition over Number.
The following query should do what you want:
CREATE TABLE #table (Number INT, Email VARCHAR(30))
INSERT INTO #table (Number, Email)
VALUES (1,'email1#email.com')
,(1,'email2#email.com')
,(1,'email3#email.com')
,(2,'email4#email.com')
,(2,'email5#email.com')
,(3,'email6#email.com')
,(4,'email7#email.com')
,(4,'email8#email.com')
SELECT *, ROW_NUMBER() OVER (PARTITION BY Number ORDER BY Number, Email) AS [RNO] INTO #temp FROM #table
DECLARE #DynamicCols NVARCHAR(MAX) = '';
DECLARE #pvt NVARCHAR(MAX) = '';
SET #pvt = STUFF(
(SELECT DISTINCT N', ' + QUOTENAME([RNO]) FROM #temp FOR XML PATH('')),1,2,N'')
SET #DynamicCols = STUFF(
(SELECT DISTINCT N', ' + QUOTENAME([RNO]) + ' AS '+ QUOTENAME('Email' + CAST([RNO] AS VARCHAR(MAX))) FROM #temp FOR XML PATH('')),1,2,N'')
EXEC (N'SELECT [Number],'+ #DynamicCols+'
FROM #temp tmp
PIVOT (MAX([Email]) FOR RNO IN('+#pvt+')) AS PIV');

how to write a query to separate each column by comma without specifying each column name

How to write a query so that each column of table1 separated by comma
Without including each column name
+------+-----+-----------+-------------+
| eno |dno | ename | job_type |
+------+-----+-----------+-------------+
| 101 | 1 | sam | manager |
| 102 | 2 | ash | teacher |
| 103 | 3 | rohan | clerk |
| 104 | 4 | sohan | peon |
| 105 | 5 | mohan | guar |
+------+-----+------------+------------+
I want to output like this
101,1,sam,manager
102,2,ash,teacher
And rest are same
With the help of a CROSS APPLY (or two), a little XML and STUFF()
A word of caution: This approach will EXCLUDE NULL values
Declare #YourTable table (eno int,dno int, ename varchar(25),job_type varchar(25))
Insert Into #YourTable values
(101,1,'sam' , 'manager'),
(102,2,'ash' , 'teacher'),
(103,3,'rohan', 'clerk' ),
(104,4,'sohan', 'peon' ),
(105,5,'mohan', 'guar' )
Select C.*
From #YourTable A
Cross Apply (Select XMLData=cast((Select A.* for XML Raw) as xml)) B
Cross Apply (
Select String=Stuff((Select ',' +Value
From (
Select Value = attr.value('.','varchar(max)')
From XMLData.nodes('/row') as A(r)
Cross Apply A.r.nodes('./#*') AS B(attr)
) X
For XML Path ('')),1,1,'')
) C
Returns
String
101,1,sam,manager
102,2,ash,teacher
103,3,rohan,clerk
104,4,sohan,peon
105,5,mohan,guar
You can also do it with a dynamic sql query.
Query
declare #sql as varchar(max);
select #sql = 'select case when right(t.csv, 1) = ' + char(39) + ',' + char(39)
+ ' then left(t.csv, len(t.csv) - 1) else t.csv end as csv from(select '
+ stuff((select '+ case when [' + column_name + '] is null then '
+ char(39) + char(39) +
' else cast([' + column_name + '] as varchar(max)) + '
+ char(39) + ',' + char(39) + ' end'
from information_schema.columns
where table_name = 'dds_emp'
order by ordinal_position asc
for xml path('')
), 1, 1, '');
select #sql += ' as csv from dds_emp)t;';
exec(#sql);

Dynamically create columns in SQL select query and join tables

I have 2 tables. They are as follows
Table : Grade
GradeID | Grade
-----------------
1 | Chopsaw
2 | Classic
3 | Chieve
Table : Moulded Quantity
Batch ID | Grade | Moulded | Date
-------------------------------------
1 | 1 | 150 | 21st May
2 | 1 | 150 | 22nd May
3 | 2 | 150 | 21st May
4 | 2 | 150 | 21st May
5 | 2 | 150 | 22nd May
I should get the Output like the following
Date | Moulded | Chopsaw | Classic | Cieve
--------------------------------------------------
21st May | 450 | 150 | 300 | 0
22nd May | 300 | 150 | 150 | 0
I am using MSSQL 2008 and i use Crystal report to display the same.
If the number of grades is known beforehand then you can do it with a static query.
SELECT date,
SUM(moulded) moulded,
SUM(CASE WHEN grade = 1 THEN moulded ELSE 0 END) Chopsaw,
SUM(CASE WHEN grade = 2 THEN moulded ELSE 0 END) Classic,
SUM(CASE WHEN grade = 3 THEN moulded ELSE 0 END) Chieve
FROM moulded_quantity
GROUP BY date
This query is not vendor specific so it should work on any major RDBMS.
Now, if the number of grades is unknown or you want it to work even if you make changes to grade table (without changing the query itself) you can resort to dynamic query. But dynamic SQL is vendor specific. Here is an example of how you can do that in MySql
SELECT CONCAT (
'SELECT date, SUM(moulded) moulded,',
GROUP_CONCAT(DISTINCT
CONCAT('SUM(CASE WHEN grade = ',gradeid,
' THEN moulded ELSE 0 END) ', grade)),
' FROM moulded_quantity GROUP BY date') INTO #sql
FROM grade;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Output (in both cases):
| DATE | MOULDED | CHOPSAW | CLASSIC | CHIEVE |
---------------------------------------------------
| 21st May | 450 | 150 | 300 | 0 |
| 22nd May | 300 | 150 | 150 | 0 |
Here is SQLFiddle demo (for both approaches).
UPDATE In Sql Server you can use STUFF and PIVOT to produce expected result with dynamic sql
DECLARE #colx NVARCHAR(MAX), #colp NVARCHAR(MAX), #sql NVARCHAR(MAX)
SET #colx = STUFF((SELECT ', ISNULL(' + QUOTENAME(Grade) + ',0) ' + QUOTENAME(Grade)
FROM grade
ORDER BY GradeID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET #colp = STUFF((SELECT DISTINCT ',' + QUOTENAME(Grade)
FROM grade
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET #sql = 'SELECT date, total moulded, ' + #colx +
' FROM
(
SELECT date, g.grade gradename, moulded,
SUM(moulded) OVER (PARTITION BY date) total
FROM moulded_quantity q JOIN grade g
ON q.grade = g.gradeid
) x
PIVOT
(
SUM(moulded) FOR gradename IN (' + #colp + ')
) p
ORDER BY date'
EXECUTE(#sql)
Output is the same as in MySql case.
Here is SQLFiddle demo.
I would suggest you before asking any question research first as it is very common question.
Updated
DECLARE #COLUMNS varchar(max)
SELECT #COLUMNS = COALESCE(#COLUMNS+'],[' ,'') + CAST(Grade as varchar)
FROM Grade
GROUP BY Grade
SET #COLUMNS = '[' + #COLUMNS + ']'
DECLARE #COLUMNS_WITH_NULL varchar(max)
SELECT #COLUMNS_WITH_NULL = COALESCE(#COLUMNS_WITH_NULL+',ISNULL([' ,'ISNULL([') + CAST(Grade as varchar) + '], 0) AS ' + CAST(Grade as varchar)
FROM Grade
GROUP BY Grade
DECLARE #COLUMNS_SUMS varchar(max)
SELECT #COLUMNS_SUMS = COALESCE(#COLUMNS_SUMS+' + ISNULL([' ,'ISNULL([') + CAST(Grade as varchar) + '], 0) '
FROM Grade
GROUP BY Grade
SET #COLUMNS_SUMS = '(' + #COLUMNS_SUMS + ') as Moulded'
PRINT #COLUMNS_SUMS
EXECUTE (
'
SELECT
Date, ' + #COLUMNS_SUMS + ', ' + #COLUMNS_WITH_NULL + '
FROM (
SELECT
m.Moulded,
m.date AS Date,
g.Grade
FROM Grade g
INNER JOIN [Moulded Quantity] m
ON m.GRADE = g.GradeID
) up
PIVOT (SUM(Moulded) FOR Grade IN ('+ #COLUMNS +')) AS pvt')