Dynamic Pivot of two columns data on single column value - sql server - sql

create table Projectdata
(
ProjectId INT,
ProjectName varchar(50),
AssociateCount INT,
Technology varchar(150),
ReportMonth INT,
Reportyear INT
)
insert into Projectdata values (111, 'ABC', 2, '.NET', 1, 2014)
insert into Projectdata values (112, 'DEF', 3, '.NET', 1, 2014)
insert into Projectdata values (113, 'XYZ', 5, 'JAVA', 1, 2014)
insert into Projectdata values (111, 'ABC', 3, 'JAVA', 2, 2014)
insert into Projectdata values (112, 'DEF', 2, '.NET', 2, 2014)
insert into Projectdata values (113, 'XYZ', 5, 'JAVA', 2, 2014)
insert into Projectdata values (112, 'DEF', 1, 'JAVA', 3, 2014)
insert into Projectdata values (113, 'XYZ', 5, 'JAVA', 3, 2014)
Select * from Projectdata gives data like
I have written a dynamic pivot query but i could't see the data in the required format.
posting my dynamic query and output
DECLARE #outputStatus nvarchar(max)
, #pivotlistStatus VARCHAR(MAX)
, #pivotlistScore VARCHAR(MAX)
SELECT
#pivotlistStatus = ISNULL(#pivotlistStatus + ',', '') + QUOTENAME(createdate1)
FROM
(
SELECT
TOP 1000 CONVERT(CHAR(3),DATENAME(MONTH, DATEADD(MONTH,ReportMonth,0) -1))+'-'+ CONVERT(VARCHAR(4),ReportYear)+'-'+'Status' as createdate1
FROM
(
SELECT
DISTINCT ReportMonth,
ReportYear
FROM
Projectdata
GROUP BY
ReportMonth,
ReportYear
)rep
ORDER BY
ReportMonth,
ReportYear
)as months1
SELECT
#pivotlistScore = ISNULL(#pivotlistScore + ',', '') + QUOTENAME(createdate1)
FROM
(
SELECT
TOP 1000 CONVERT(CHAR(3),DATENAME(MONTH, DATEADD(MONTH,ReportMonth,0) -1))+'-'+ CONVERT(VARCHAR(4),ReportYear)+'-'+'Score' as createdate1
FROM
(
SELECT
DISTINCT ReportMonth,
ReportYear
FROM
Projectdata
GROUP BY
ReportMonth,
ReportYear
)rep
ORDER BY
ReportMonth,
reportyear
)as months
SET #outputStatus = N'
SELECT
ProjectId,
ProjectName,
' + #pivotlistStatus + '
,' + #pivotlistScore +'
FROM
(SELECT
DISTINCT
ProjectId,
ProjectName,
CONVERT(CHAR(3),DATENAME(MONTH, DATEADD(MONTH,ReportMonth,0) -1))+''-''+ CONVERT(VARCHAR(4),ReportYear)+''-''+''Status'' AS CreatedateStatus ,
CONVERT(CHAR(3),DATENAME(MONTH, DATEADD(MONTH,ReportMonth,0) -1))+''-''+ CONVERT(VARCHAR(4),ReportYear)+''-''+''Score'' AS CreatedateScore ,
AssociateCount,
Technology
FROM
Projectdata
) pvtunion
PIVOT ( MAX(Technology) FOR CreatedateStatus IN (' + #pivotlistStatus + ') ) AS PVTstatus
PIVOT ( SUM(AssociateCount) FOR CreatedateScore IN (' + #pivotlistScore + ') ) AS PVTScore
ORDER BY ProjectId'
EXEC sp_executesql #outputStatus
But i need the one project data in a single row... i could see the result as 8 rows but i need the ouput in 3 rows as below
could some one help me out pls.....

Related

SQL LEFT JOIN to many categories

Suppose the following easy scenario, where a product row gets connected to one primary category, subcategory, and sub-subcategory.
DECLARE #PRODUCTS TABLE (ID int, DESCRIPTION varchar(50), CAT varchar(30), SUBCAT varchar(30), SUBSUBCAT varchar(30));
INSERT #PRODUCTS (ID, DESCRIPTION, CAT, SUBCAT, SUBSUBCAT) VALUES
(1, 'NIKE MILLENIUM', '1', '10', '100'),
(2, 'NIKE CORTEZ', '1', '12', '104'),
(3, 'ADIDAS PANTS', '2', '27', '238'),
(4, 'PUMA REVOLUTION 5', '3', '35', '374'),
(5, 'SALOMON SHELTER CS', '4', '15', '135'),
(6, 'NIKE EBERNON LOW', '2', '14', '157');
DECLARE #CATS TABLE (ID int, DESCR varchar(100));
INSERT #CATS (ID, DESCR) VALUES
(1, 'MEN'),
(2, 'WOMEN'),
(3, 'UNISEX'),
(4, 'KIDS'),
(5, 'TEENS'),
(6, 'BACK TO SCHOOL');
DECLARE #SUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBCATS (ID, DESCR) VALUES
(10, 'FOOTWEAR'),
(12, 'OUTERWEAR'),
(14, 'SWIMWEAR'),
(15, 'HOODIES'),
(27, 'CLOTHING'),
(35, 'SPORTS');
DECLARE #SUBSUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBSUBCATS (ID, DESCR) VALUES
(100, 'RUNNING'),
(104, 'ZIP TOPS'),
(135, 'FLEECE'),
(157, 'BIKINIS'),
(238, 'PANTS'),
(374, 'JOGGERS');
SELECT prod.ID,
prod.DESCRIPTION,
CONCAT(cat1.DESCR, ' > ', cat2.DESCR, ' > ', cat3.DESCR) AS CATEGORIES
FROM #PRODUCTS AS prod
LEFT JOIN #CATS AS cat1 ON cat1.ID = prod.CAT
LEFT JOIN #SUBCATS AS cat2 ON cat2.ID = prod.SUBCAT
LEFT JOIN #SUBSUBCATS AS cat3 ON cat3.ID = prod.SUBSUBCAT;
Now suppose that the foreign keys on #PRODUCTS table aren't just indices to their respective tables. They are comma-separated indices to more than one categories, subcategories, and sub-subcategories like here.
DECLARE #PRODUCTS TABLE (ID int, DESCRIPTION varchar(50), CAT varchar(30), SUBCAT varchar(30), SUBSUBCAT varchar(30));
INSERT #PRODUCTS (ID, DESCRIPTION, CAT, SUBCAT, SUBSUBCAT) VALUES
(1, 'NIKE MILLENIUM', '1, 2', '10, 12', '100, 135'),
(2, 'NIKE CORTEZ', '1, 5', '12, 15', '104, 374'),
(3, 'ADIDAS PANTS', '2, 6', '27, 35', '238, 374');
DECLARE #CATS TABLE (ID int, DESCR varchar(100));
INSERT #CATS (ID, DESCR) VALUES
(1, 'MEN'),
(2, 'WOMEN'),
(3, 'UNISEX'),
(4, 'KIDS'),
(5, 'TEENS'),
(6, 'BACK TO SCHOOL');
DECLARE #SUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBCATS (ID, DESCR) VALUES
(10, 'FOOTWEAR'),
(12, 'OUTERWEAR'),
(14, 'SWIMWEAR'),
(15, 'HOODIES'),
(27, 'CLOTHING'),
(35, 'SPORTS');
DECLARE #SUBSUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBSUBCATS (ID, DESCR) VALUES
(100, 'RUNNING'),
(104, 'ZIP TOPS'),
(135, 'FLEECE'),
(157, 'BIKINIS'),
(238, 'PANTS'),
(374, 'JOGGERS');
SELECT prod.ID,
prod.DESCRIPTION
--CONCAT(cat1.DESCR, ' > ', cat2.DESCR, ' > ', cat3.DESCR) AS CATEGORIES
FROM #PRODUCTS AS prod
--LEFT JOIN #CATS AS cat1 ON cat1.ID = prod.CAT
--LEFT JOIN #SUBCATS AS cat2 ON cat2.ID = prod.SUBCAT
--LEFT JOIN #SUBSUBCATS AS cat3 ON cat3.ID = prod.SUBSUBCAT;
In this case I want to achieve the following:
Be able to retrieve the respective names of the cats, subcats, sub-subcats, ie. for cats '1, 2' be able to retrieve their names (I tried LEFT JOIN #CATS AS cat1 ON cat1.ID IN prod.CAT but it doesn't work)
Create triplets of the corresponding cats, subcats, sub-subcats, ie. for
cats '1, 2'
subcats '12, 17'
sub-subcats '239, 372'
(after retrieving the appropriate names) create pipe-separated category routes like name of cat 1 > name of subcat 12 > name of sub-subcat 239 | name of cat 2 > name of subcat 17 > name of sub-subcat 372
So, for a row like (1, 'NIKE MILLENIUM', '1, 2', '10, 12', '100, 135'),
I would like to get the following result
ID
DESCRIPTION
CATEGORIES
1
NIKE MILLENIUM
MEN > FOOTWEAR > RUNNING # WOMEN > OUTERWEAR > FLEECE (I had to use # as the delimiter of the two triplets because pipe messed with the table's columns)
In case the user stupidly stores more cat IDs than subcat IDs, or sub-subcat IDs, the query should just match the ones that have a corresponding position match, ie for
cats '1, 2'
subcats '12'
sub-subcats '239, 372'
it should just create one triplet, like name of 1 > name of 12 > name of 239
STRING_SPLIT() does not promise to return the values in a specific order, so it won't work in this case as ordinal position matters.
Use OPENJSON() split the string into separate rows to ensure the values are returned in the same order.
OPENJSON() also returns a key field, so you can join on the row number within each grouping. You'll want an INNER JOIN since your requirement is that all values in that "column" must exist.
Use STUFF() to assemble the various cat>subcat>subsubcat values.
DECLARE #PRODUCTS TABLE (ID int, DESCRIPTION varchar(50), CAT varchar(30), SUBCAT varchar(30), SUBSUBCAT varchar(30));
INSERT #PRODUCTS (ID, DESCRIPTION, CAT, SUBCAT, SUBSUBCAT) VALUES
(1, 'NIKE MILLENIUM', '1, 2', '10, 12', '100, 135'),
(2, 'NIKE CORTEZ', '1, 5', '12, 15', '104, 374'),
(3, 'ADIDAS PANTS', '2, 6, 1', '27, 35, 10', '238, 374, 100'),
(4, 'JOE THE PLUMBER JEANS', '1, 5', '27', '238, 374');
DECLARE #CATS TABLE (ID int, DESCR varchar(100));
INSERT #CATS (ID, DESCR) VALUES
(1, 'MEN'),
(2, 'WOMEN'),
(3, 'UNISEX'),
(4, 'KIDS'),
(5, 'TEENS'),
(6, 'BACK TO SCHOOL');
DECLARE #SUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBCATS (ID, DESCR) VALUES
(10, 'FOOTWEAR'),
(12, 'OUTERWEAR'),
(14, 'SWIMWEAR'),
(15, 'HOODIES'),
(27, 'CLOTHING'),
(35, 'SPORTS');
DECLARE #SUBSUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBSUBCATS (ID, DESCR) VALUES
(100, 'RUNNING'),
(104, 'ZIP TOPS'),
(135, 'FLEECE'),
(157, 'BIKINIS'),
(238, 'PANTS'),
(374, 'JOGGERS');
;
with prod as (
SELECT p.ID,
p.DESCRIPTION
--CONCAT(cat1.DESCR, ' > ', cat2.DESCR, ' > ', cat3.DESCR) AS CATEGORIES
, c.value as CatId
, c.[key] as CatKey
, sc.value as SubCatId
, sc.[key] as SubCatKey
, ssc.value as SubSubCatId
, ssc.[key] as SubSubCatKey
FROM #PRODUCTS p
cross apply OPENJSON(CONCAT('["', REPLACE(cat, ', ', '","'), '"]')) c
cross apply OPENJSON(CONCAT('["', REPLACE(subcat, ', ', '","'), '"]')) sc
cross apply OPENJSON(CONCAT('["', REPLACE(subsubcat, ', ', '","'), '"]')) ssc
where c.[key] = sc.[key]
and c.[key] = ssc.[key]
)
, a as (
select p.ID
, p.DESCRIPTION
, c.DESCR + ' > ' + sc.DESCR + ' > ' + ssc.DESCR as CATEGORIES
, p.CatKey
from prod p
inner join #CATS c on c.ID = p.CatId
inner join #SUBCATS sc on sc.ID = p.SubCatId
inner join #SUBSUBCATS ssc on ssc.ID = p.SubSubCatId
)
select DISTINCT ID
, DESCRIPTION
, replace(STUFF((SELECT distinct ' | ' + a2.CATEGORIES
from a a2
where a.ID = a2.ID
FOR XML PATH(''))
,1,2,''), '>', '>') CATEGORIES
from a
Totally separate answer because of the change to older technology. I think my original answer is still good for folks using current SQL Server versions, so I don't want to remove it.
I don't remember where I got the function. When I found it today it was named split_delimiter. I changed the name, added some comments, and incorporated the ability to have a delimiter that is more than one character long.
CREATE FUNCTION [dbo].[udf_split_string](#delimited_string VARCHAR(8000), #delimiter varchar(10))
RETURNS TABLE AS
RETURN
WITH cte10(num) AS ( -- 10 rows
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
)
, cte100(num) AS ( -- 100 rows
SELECT 1
FROM cte10 t1, cte10 t2
)
, cte10000(num) AS ( -- 10000 rows
SELECT 1
FROM cte100 t1, cte100 t2
)
, cte1(num) AS ( -- 1 row per character
SELECT TOP (ISNULL(DATALENGTH(#delimited_string), 0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM cte10000
)
, cte2(num) AS ( -- locations of strings
SELECT 1
UNION ALL
SELECT t.num + len(replace(#delimiter, ' ', '_'))
FROM cte1 t
WHERE SUBSTRING(#delimited_string, t.num, len(replace(#delimiter, ' ', '_'))) = #delimiter
)
, cte3(num, [len]) AS (
SELECT t.num
, ISNULL(NULLIF(CHARINDEX(#delimiter, #delimited_string, t.num), 0) - t.num, 8000)
FROM cte2 t
)
SELECT [Key] = ROW_NUMBER() OVER (ORDER BY t.num)
, [Value] = SUBSTRING(#delimited_string, t.num, t.[len])
FROM cte3 t;
GO
DECLARE #PRODUCTS TABLE (ID int, DESCRIPTION varchar(50), CAT varchar(30), SUBCAT varchar(30), SUBSUBCAT varchar(30));
INSERT #PRODUCTS (ID, DESCRIPTION, CAT, SUBCAT, SUBSUBCAT) VALUES
(1, 'NIKE MILLENIUM', '1, 2', '10, 12', '100, 135'),
(2, 'NIKE CORTEZ', '1, 5', '12, 15', '104, 374'),
(3, 'ADIDAS PANTS', '2, 6, 1', '27, 35, 10', '238, 374, 100'),
(4, 'JOE THE PLUMBER JEANS', '1, 5', '27', '238, 374');
DECLARE #CATS TABLE (ID int, DESCR varchar(100));
INSERT #CATS (ID, DESCR) VALUES
(1, 'MEN'),
(2, 'WOMEN'),
(3, 'UNISEX'),
(4, 'KIDS'),
(5, 'TEENS'),
(6, 'BACK TO SCHOOL');
DECLARE #SUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBCATS (ID, DESCR) VALUES
(10, 'FOOTWEAR'),
(12, 'OUTERWEAR'),
(14, 'SWIMWEAR'),
(15, 'HOODIES'),
(27, 'CLOTHING'),
(35, 'SPORTS');
DECLARE #SUBSUBCATS TABLE (ID int, DESCR varchar(100));
INSERT #SUBSUBCATS (ID, DESCR) VALUES
(100, 'RUNNING'),
(104, 'ZIP TOPS'),
(135, 'FLEECE'),
(157, 'BIKINIS'),
(238, 'PANTS'),
(374, 'JOGGERS');
;
with prod as (
SELECT p.ID,
p.DESCRIPTION
, c.value as CatId
, c.[key] as CatKey
, sc.value as SubCatId
, sc.[key] as SubCatKey
, ssc.value as SubSubCatId
, ssc.[key] as SubSubCatKey
FROM #PRODUCTS p
cross apply dbo.udf_split_string(cat, ', ') c
cross apply dbo.udf_split_string(subcat, ', ') sc
cross apply dbo.udf_split_string(subsubcat, ', ') ssc
where c.[key] = sc.[key]
and c.[key] = ssc.[key]
)
, a as (
select p.ID
, p.DESCRIPTION
, c.DESCR + ' > ' + sc.DESCR + ' > ' + ssc.DESCR as CATEGORIES
, p.CatKey
from prod p
inner join #CATS c on c.ID = p.CatId
inner join #SUBCATS sc on sc.ID = p.SubCatId
inner join #SUBSUBCATS ssc on ssc.ID = p.SubSubCatId
)
select DISTINCT ID
, DESCRIPTION
, replace(STUFF((SELECT distinct ' | ' + a2.CATEGORIES
from a a2
where a.ID = a2.ID
FOR XML PATH(''))
,1,2,''), '>', '>') CATEGORIES
from a
Well that should do work, i changed your character ">" for "-" just for see the data more simple.
the design of your tables is not perfect but the first try almost never is.
select mainp.ID, mainp.DESCRIPTION, stuff(ppaths.metapaths, len(ppaths.metapaths),1,'') metalinks
from #PRODUCTS mainp
cross apply(
select
(select
c.DESCR + '-' + sc.DESCR + '-' + sbc.DESCR + '|'
from #PRODUCTS p
cross apply (select row_number() over(order by Value) id, Value from split(p.CAT, ','))cat_ids
inner join #cats c on c.ID = cat_ids.Value
cross apply (select row_number() over(order by Value) id, Value from split(p.SUBCAT, ','))subcat_ids
inner join #SUBCATS sc on sc.ID = subcat_ids.Value
and subcat_ids.id = subcat_ids.id
cross apply (select row_number() over(order by Value) id, Value from split(p.SUBSUBCAT, ','))subsubcat_ids
inner join #SUBSUBCATS sbc on sbc.ID = subsubcat_ids.Value
and subsubcat_ids.id = subcat_ids.id
where p.id = mainp.ID
for xml path('')) metapaths
) ppaths
the link for split function
https://desarrolladores.me/2014/03/sql-server-funcion-split-para-dividir-un-string/

How to add pagination to this dynamic sql

I have the following table with its respective data
CREATE TABLE [dbo].[Columns]
(
[ColumnId] INT,
[TableId] INT NOT NULL,
[ColumnName] NVARCHAR(150) NOT NULL,
[Order] INT,
[Key] BIT
)
CREATE TABLE [dbo].[Tables]
(
[TableId] INT,
[TableName] NVARCHAR(200),
[DistrictId] INT
)
CREATE TABLE [dbo].[RowValues]
(
[ColumnId] INT NOT NULL,
[RowNumber] INT NOT NULL,
[Value] NVARCHAR(200) NOT NULL
)
insert into [Columns] values (1, 1, 'StudentName', 1, 1)
insert into [Columns] values (2, 1, 'Grade', 1, 0)
insert into [Columns] values (3, 1, 'Year', 1, 0)
insert into [Columns] values (4, 1, 'Section', 1, 0)
insert into [Columns] values (5, 2, 'TeacherName', 1, 1)
insert into [Columns] values (6, 2, 'Department', 1, 0)
insert into [Tables] values (1, 'Student', 1)
insert into [Tables] values (2, 'Teacher', 1)
insert into [RowValues] values (1, 1, 'Student Alan')
insert into [RowValues] values (2, 1, '99')
insert into [RowValues] values (3, 1, '1st')
insert into [RowValues] values (4, 1, 'Section 1')
insert into [RowValues] values (1, 2, 'Student Alex')
insert into [RowValues] values (2, 2, '98')
insert into [RowValues] values (3, 2, '1st')
insert into [RowValues] values (4, 2, 'Section 1')
insert into [RowValues] values (1, 3, 'Student Alfonso')
insert into [RowValues] values (2, 3, '97')
insert into [RowValues] values (3, 3, '1st')
insert into [RowValues] values (4, 3, 'Section 1')
insert into [RowValues] values (1, 4, 'Student Ben')
insert into [RowValues] values (2, 4, '96')
insert into [RowValues] values (3, 4, '1st')
insert into [RowValues] values (4, 4, 'Section 1')
insert into [RowValues] values (1, 5, 'Student Cathy')
insert into [RowValues] values (2, 5, '95')
insert into [RowValues] values (3, 5, '1st')
insert into [RowValues] values (4, 5, 'Section 1')
insert into [RowValues] values (5, 1, 'Teacher Tesso')
insert into [RowValues] values (6, 1, 'Biology Dept')
insert into [RowValues] values (5, 2, 'Teacher Marvin')
insert into [RowValues] values (6, 2, 'Math Dept')
I wanted to be able to sort the dynamic column
example sort by 'StudentName' ASC it would sort data using column returning
When sorting by StudentName:
StudentName Grade Year Section
'Student Alan' 99 '1st' 'Section 1'
'Student Alex' 98 '1st' 'Section 1'
'Student Alfonso' 97 '1st' 'Section 1'
.
.
.
When sorting by Grade ASC:
StudentName Grade Year Section
'Student Cathy' 95 '1st' 'Section 1'
'Student Ben' 96 '1st' 'Section 1'
'Student Alfonso' 97 '1st' 'Section 1'
.
.
.
When sorting by TeacherName ASC (different table)
TeacherName Department
'Teacher Marvin' 'Math Dept'
'Teacher Tesso' 'Biology Dept'
.
.
.
I have manage to accomplish this.
The problem is adding Pagination to my dynamic SQL string.
This is my stored procedure
CREATE PROCEDURE [dbo].[usp_DynamicSearch_Paged]
(#districtId INT,
#searchTerm NVARCHAR(max),
#pageNumber INT = 1,
#pageSize INT = 10,
#sortColumn NVARCHAR(20),
#sortDirection INT)
AS
BEGIN
DECLARE #columns nvarchar(max),
#sql nvarchar(max),
#rows int
SET #rows = (#pageNumber - 1) * #pageSize;
SELECT
#columns = (SELECT ',' + QUOTENAME(ColumnName)
FROM Tables AS T
INNER JOIN Columns AS C ON T.TableId = C.TableId
WHERE T.districtId = #districtId
ORDER BY C.[Order]
FOR XML PATH(''))
SELECT
#columns = (SELECT ',' + QUOTENAME(ColumnName)
FROM Tables AS T
INNER JOIN Columns AS C ON T.TableId = C.TableId
WHERE T.districtId = #districtId
ORDER BY C.[Order]
FOR XML PATH(''))
SELECT [Columns] = REPLACE(REPLACE(value,'[',''),']','')
FROM STRING_SPLIT(STUFF(#Columns, 1, 1, ''),',')
SET #sql = N'
SELECT * INTO #Fields FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY ColumnName ORDER BY (SELECT NULL)) RN,
districtId,
ColumnName
, V.[Value]
FROM Tables AS T
INNER JOIN Columns AS C
ON T.TableId = C.TableId
LEFT OUTER JOIN RowValues AS V
ON C.ColumnId = V.ColumnId
) t
PIVOT (
MIN([Value])
FOR [ColumnName]
IN ('
+ STUFF(#Columns, 1, 1, '') +
')
) AS PivotTable
DECLARE #KeyColumnName NVARCHAR(100)
SELECT #KeyColumnName = ColumnName
FROM Tables AS T
INNER JOIN Columns AS C
ON T.TableId = C.TableId
WHERE T.districtId = ' + CAST(#districtId AS VARCHAR) + '
AND C.IsKey = 1
DECLARE #sql NVARCHAR(MAX)
SET #SQL = ''
SELECT *
FROM #Fields
WHERE '' + #KeyColumnName + '' LIKE '''''+ #searchTerm +'%''''
''
OFFSET ('+CAST(#rows AS VARCHAR)+') ROWS
FETCH NEXT ' +CAST(#pageSize AS VARCHAR) +' ROWS ONLY;
EXEC sp_EXECUTESQL #sql
'
EXEC sp_executesql #sql
END
I just added the
OFFSET ('+CAST(#rows AS VARCHAR)+') ROWS
FETCH NEXT ' +CAST(#pageSize AS VARCHAR) +' ROWS ONLY;
EXEC sp_EXECUTESQL #sql
and now it doesn't work
The OFFSET and FETCH clauses are the options of the ORDER BY clause. They allow you to limit the number of rows to be returned by a query.
https://www.sqlservertutorial.net/sql-server-basics/sql-server-offset-fetch/
I think you need to declare ORDER BY

SQL query cast from a group

I'm trying to make a query whit a 'cast group by' - output.
But not quit sure how to tackle this or even to start (I think i need cast and group by but not sure).
I have some code below which hopefully explains what I'm trying to do.
Could somebody help me to make a query to have the correct output?
CREATE TABLE buyers
(
id int,
buyer_name varchar(20)
);
INSERT INTO buyers
VALUES (1, 'harry'), (2, 'zoe'), (3, 'rose');
CREATE TABLE grocery
(
id int,
name VARCHAR(20),
id_buyers int
);
INSERT INTO grocery
VALUES (1, 'milk', 1), (2, 'milk', 1), (3, 'ham', 1), (4, 'bread', 2),
(5, 'bread', 2), (6, 'bread', 2), (6, 'milk', 2), (7, 'milk', 2),
(8, 'ham', 3);
CREATE TABLE wanted_output
(
name VARCHAR(20),
stuffed_lists VARCHAR(20)
);
INSERT INTO wanted_output
VALUES ('harry', '2x milk, 1x ham'), ('zoe', '3x bread, 2x milk'),
('rose', '1x ham ');
EDIT :
at this point I have this (not working):
SELECT
buyers.buyer_name,
COALESCE(
STUFF(
(SELECT ' , ' +
CAST( grocery.name AS varchar(max))
from grocery
where grocery.id_buyers = buyers.id
FOR XML PATH('')
), 1, 2, '' ),'')
AS wanted_output
FROM buyers
nvm afther some fideling :
SELECT
buyers.buyer_name,
COALESCE(
STUFF(
(SELECT ' , ' + cast(count(*) as varchar(4)) + ' x ' +
CAST( grocery.name AS varchar(max))
from grocery
where grocery.id_buyers = buyers.id
group by grocery.name
FOR XML PATH('')
), 1, 2, '' ),'')
AS wanted_output
FROM buyers

Pivot values on column based on grouped columns in SQL

I want to pivot values to columns based on a group. However, I do not know the values beforehand.
A query gives me this result.
Id Code EntityId
----------- ------------ -------------
3 22209776 1
4 143687971 3
4 143687971 4
4 143687971 5
4 143687971 15
5 143658155 7
5 143658155 8
I would like to output this
Id Code EntityId1 EntityId2 EntityId3 EntityId4
----------- ------------ ------------- ------------- ------------- -------------
3 22209776 1 NULL NULL NULL
4 143687971 3 4 5 15
5 143658155 7 8 NULL NULL
If you do now know how many column you are going to have in the result, you need to use dynamic T-SQL statement to build the PIVOT. For example:
IF OBJECT_ID('tempdb..#DataSource') IS NOT NULL
BEGIN;
DROP TABLE #DataSource;
END;
CREATE TABLE #DataSource
(
[id] INT
,[Code] INT
,[EntityId] INT
);
DECLARE #DynamicTSQLStatement NVARCHAR(MAX)
,#Columns NVARCHAR(MAX);
DECLARE #MaxColumns INT;
INSERT INTO #DataSource ([id], [Code], [EntityId])
VALUES (3, 22209776 , 1)
,(4, 143687971, 3)
,(4, 143687971, 4)
,(4, 143687971, 5)
,(4, 143687971, 15)
,(5, 143658155, 7)
,(5, 143658155, 8)
,(4, 143687971, 25)
,(4, 143687971, 26);
-- we need to know how many columns are going to be shown
SELECT TOP 1 #MaxColumns = COUNT(*)
FROM #DataSource
GROUP BY [Code]
ORDER BY COUNT(*) DESC;
-- we are building here the following string '[1],[2],[3],[4],[5],[6]';
-- this will change depending the input data
WITH gen AS
(
SELECT 1 AS num
UNION ALL
SELECT num+1
FROM gen
WHERE num+1<=#MaxColumns
)
SELECT #Columns = STUFF
(
(
SELECT ',[EntityId' + CAST([num] AS VARCHAR(12)) + ']'
FROM gen
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1
,1
,''
)
OPTION (maxrecursion 10000);
SET #DynamicTSQLStatement = N'
SELECT *
FROM
(
SELECT [id]
,[Code]
,[EntityId]
,''EntityId'' + CAST(ROW_NUMBER() OVER(PARTITION BY [Code] ORDER BY [EntityId]) AS VARCHAR(12))
FROM #DataSource
) DS ([id], [Code], [EntityId], [RowID])
PIVOT
(
MAX([EntityId]) for [RowID] in (' + #Columns +')
) PVT;';
EXEC sp_executesql #DynamicTSQLStatement;
You could try using the pivot function:
declare #tmp TABLE (id int, Code int, EntityId NVARCHAR(10))
insert into #tmp (id, Code, EntityId)
values (3, 22209776 , 1),
(4, 143687971, 3),
(4, 143687971, 4),
(4, 143687971, 5),
(4, 143687971, 15),
(5, 143658155, 7),
(5, 143658155, 8)
select
pvt.id
,pvt.Code
,[1] as EntityID1
,[2] as EntityID2
,[3] as EntityID3
,[4] as EntityID4
from (
select
id, Code, EntityId
,ROW_NUMBER() over(partition by code order by EntityId) as RowNum
from
#tmp
) a
pivot (MAX(EntityId) for RowNum in ([1], [2], [3], [4])) as pvt

SQL Server 2008 R2 - Calculation referencing Previous Row

I am looking to design a query, where a calculation compares a value in a cell with a value in the previous cell in the same column, and another calculation uses the previous calculations result to reference a previous cell for a calculation as well. The data will be in the following order from the sample image below - Material, Plant and YearWeek
Sample Data Image
From the image below, the blue column headers represent the raw data, and the yellow column headers represent the calculation rows.
The formulae for the calculation rows are as follows:
First? = IF(AND(B2=B1,C2=C1),"No","First")
Actual Available = IF(F2="First",D2-E2,G1-E2)
From my investigation, the LEAD and LAG functions can help accomplish this, but since I am restricted to SQL Server 2008 R2, I am unable to use them. Please find the query to create the table.
CREATE TABLE ZDAYS ([YearWeek] VARCHAR(7),
[Material] VARCHAR(3), [Plant] VARCHAR(3),
[Inventory] INT, [Demand] INT)
INSERT INTO ZDAYS VALUES ('2015-42', 'ABC', '101', 20, 5)
INSERT INTO ZDAYS VALUES ('2015-43', 'ABC', '101', 20, 3)
INSERT INTO ZDAYS VALUES ('2015-44', 'ABC', '101', 20, 2)
INSERT INTO ZDAYS VALUES ('2015-42', 'ABC', '201', 30, 10)
INSERT INTO ZDAYS VALUES ('2015-43', 'ABC', '201', 30, 8)
INSERT INTO ZDAYS VALUES ('2015-44', 'ABC', '201', 30, 4)
INSERT INTO ZDAYS VALUES ('2015-42', 'XYZ', '101', 10, 3)
INSERT INTO ZDAYS VALUES ('2015-43', 'XYZ', '101', 10, 2)
INSERT INTO ZDAYS VALUES ('2015-44', 'XYZ', '201', 20, 4)
Final Data Output
YearWeek Material Plant Inventory Demand First? Actual Available
2015-42 ABC 101 20 5 First 15
2015-43 ABC 101 20 3 No 12
2015-44 ABC 101 20 2 No 10
2015-42 ABC 201 30 10 First 20
2015-43 ABC 201 30 8 No 12
2015-44 ABC 201 30 4 No 8
2015-42 XYZ 101 10 3 First 7
2015-43 XYZ 101 10 2 No 5
2015-44 XYZ 201 20 4 First 16
Adapted from answer 'No Joins and No Analytic Functions' at:
http://blog.sqlauthority.com/2011/11/24/sql-server-solution-to-puzzle-simulate-lead-and-lag-without-using-sql-server-2012-analytic-function/
declare #ZDAYS TABLE ([YearWeek] VARCHAR(7),
[Material] VARCHAR(3), [Plant] VARCHAR(3),
[Inventory] INT, [Demand] INT)
INSERT INTO #ZDAYS VALUES ('2015-42', 'ABC', '101', 20, 5)
INSERT INTO #ZDAYS VALUES ('2015-43', 'ABC', '101', 20, 3)
INSERT INTO #ZDAYS VALUES ('2015-44', 'ABC', '101', 20, 2)
INSERT INTO #ZDAYS VALUES ('2015-42', 'ABC', '201', 30, 10)
INSERT INTO #ZDAYS VALUES ('2015-43', 'ABC', '201', 30, 8)
INSERT INTO #ZDAYS VALUES ('2015-44', 'ABC', '201', 30, 4)
INSERT INTO #ZDAYS VALUES ('2015-42', 'XYZ', '101', 10, 3)
INSERT INTO #ZDAYS VALUES ('2015-43', 'XYZ', '101', 10, 2)
INSERT INTO #ZDAYS VALUES ('2015-44', 'XYZ', '201', 20, 4);
WITH T1 (RowNum, UniqueID, YearWeek, Material, Plant, Inventory, Demand)
AS
(SELECT Row_Number() OVER(ORDER BY z.Material,z.Plant,z.YearWeek ) N
,1.0 + floor(10000 * RAND(convert(varbinary, newid()))) as UniqueID
,z.YearWeek
,z.Material
,z.Plant
,z.Inventory
,z.Demand
FROM #ZDAYS z
)
select T1.*,
CASE WHEN RowNum%2=1 THEN MAX(CASE WHEN RowNum%2=0 THEN UniqueID END) OVER (Partition BY (RowNum+1)/2) ELSE MAX(CASE WHEN RowNum%2=1 THEN UniqueID END) OVER (Partition BY RowNum/2) END LeadValUniqueID,
CASE WHEN RowNum%2=1 THEN MAX(CASE WHEN RowNum%2=0 THEN UniqueID END) OVER (Partition BY RowNum/2) ELSE MAX(CASE WHEN RowNum%2=1 THEN UniqueID END) OVER (Partition BY (RowNum+1)/2) END LagValUniqueID
FROM T1
ORDER BY T1.Material, T1.Plant, T1.YearWeek
GO
or, the same logic with the Lead() and Lag() rows concatenated for identification instead of generating a unique id.
declare #ZDAYS TABLE ([YearWeek] VARCHAR(7),
[Material] VARCHAR(3), [Plant] VARCHAR(3),
[Inventory] INT, [Demand] INT)
INSERT INTO #ZDAYS VALUES ('2015-42', 'ABC', '101', 20, 5)
INSERT INTO #ZDAYS VALUES ('2015-43', 'ABC', '101', 20, 3)
INSERT INTO #ZDAYS VALUES ('2015-44', 'ABC', '101', 20, 2)
INSERT INTO #ZDAYS VALUES ('2015-42', 'ABC', '201', 30, 10)
INSERT INTO #ZDAYS VALUES ('2015-43', 'ABC', '201', 30, 8)
INSERT INTO #ZDAYS VALUES ('2015-44', 'ABC', '201', 30, 4)
INSERT INTO #ZDAYS VALUES ('2015-42', 'XYZ', '101', 10, 3)
INSERT INTO #ZDAYS VALUES ('2015-43', 'XYZ', '101', 10, 2)
INSERT INTO #ZDAYS VALUES ('2015-44', 'XYZ', '201', 20, 4);
-- LAG and LEAD result rows concatenated
WITH T1 (RowNum, YearWeek, Material, Plant, Inventory, Demand)
AS
(SELECT Row_Number() OVER(ORDER BY z.Material,z.Plant,z.YearWeek ) N
,z.YearWeek
,z.Material
,z.Plant
,z.Inventory
,z.Demand
FROM #ZDAYS z
)
select T1.*,
CASE WHEN RowNum%2=1 THEN MAX(CASE WHEN RowNum%2=0 THEN YearWeek + ' ' + Material + ' ' + Plant + ' ' + cast(Inventory as varchar(5)) + ' ' + cast(Demand as varchar(5)) END) OVER (Partition BY (RowNum+1)/2) ELSE MAX(CASE WHEN RowNum%2=1 THEN YearWeek + ' ' + Material + ' ' + Plant + ' ' + cast(Inventory as varchar(5)) + ' ' + cast(Demand as varchar(5)) END) OVER (Partition BY RowNum/2) END LeadRowValues,
CASE WHEN RowNum%2=1 THEN MAX(CASE WHEN RowNum%2=0 THEN YearWeek + ' ' + Material + ' ' + Plant + ' ' + cast(Inventory as varchar(5)) + ' ' + cast(Demand as varchar(5)) END) OVER (Partition BY RowNum/2) ELSE MAX(CASE WHEN RowNum%2=1 THEN YearWeek + ' ' + Material + ' ' + Plant + ' ' + cast(Inventory as varchar(5)) + ' ' + cast(Demand as varchar(5)) END) OVER (Partition BY (RowNum+1)/2) END LagRowValues
FROM T1
ORDER BY T1.Material, T1.Plant, T1.YearWeek
GO
In earlier versions of SQL Server you can use apply:
select z.yearweek, z.material, z.plant, z.inventory, z.demand,
(case when seqnum = 1 then 'Yes' else 'No' end) as isFirst,
(inventory - cume.demand) as ActualAvailable
from (select z.*,
row_number() over (partition by material, plant order by yearweek) as seqnum
from zdays z
) z outer apply
(select sum(z2.demand) as demand
from zdays z2
where z2.material = z.material and z2.plant = z.plant and
z2.yearweek <= z.yearweek
) cume