How to order by dynamic column in TSQL? - sql

I have these tables
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)
)
CREATE TABLE [dbo].[RowValues]
(
[ColumnId] INT NOT NULL,
[RowNumber] INT NOT NULL,
[Value] NVARCHAR(200) NOT NULL
)
With this sample data:
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')
insert into [Tables] values (2, 'Teacher')
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 have this stored procedure:
CREATE PROCEDURE [dbo].[usp_DynamicSearch_Paged]
(#searchTerm NVARCHAR(max),
#pageNumber INT = 1,
#pageSize INT = 10,
#sortColumn NVARCHAR(20),
#sortDirection INT)
AS
BEGIN
DECLARE #TableNameLiteral nvarchar(13) = 'TableName'
DECLARE #ColumnNameLiteral nvarchar(10) = 'ColumnName'
IF (ISNULL(#sortColumn, '') = '')
BEGIN
SET #sortColumn = #TableNameLiteral
END
;WITH KeyTableId AS
(
SELECT
T.TableId
FROM
[dbo].[Tables] T
INNER JOIN
[dbo].[Columns] C ON T.TableId = C.[TableId]
WHERE
C.[Key] = 1
), ColumnId AS
(
SELECT
[KeyValue] = C.[ColumnName]
,[ColumnId] = V.[ColumnId]
,V.[Value]
,T.[TableName]
,C.[ColumnName]
,C.[Order]
,C.[Key]
FROM
[dbo].[Tables] T
INNER JOIN
[dbo].[Columns] C ON T.TableId = C.[TableId]
LEFT JOIN
[dbo].[RowValues] V ON V.[ColumnId] = C.[ColumnId]
RIGHT JOIN
KeyTableId KT ON T.TableId = KT.TableId
)
SELECT *
FROM ColumnId
WHERE ISNULL(#SearchTerm,'') = ''
OR [Value] LIKE #SearchTerm + '%'
ORDER BY
CASE WHEN #sortDirection = 2 THEN
CASE
WHEN #sortColumn = #TableNameLiteral THEN [TableName]
WHEN #sortColumn = #ColumnNameLiteral THEN [ColumnName]
END
END DESC,
CASE WHEN #sortDirection = 1 THEN
CASE
WHEN #sortColumn = #TableNameLiteral THEN [TableName]
WHEN #sortColumn = #ColumnNameLiteral THEN [ColumnName]
END
END ASC
OFFSET ((#pageNumber - 1) * #pageSize) ROWS
FETCH NEXT #PageSize ROWS ONLY;
SELECT
ColumnId = C.ColumnId,
C.ColumnName,
C.[Order],
C.[Key]
FROM [dbo].[Tables] T
LEFT JOIN [dbo].[Columns] C ON T.TableId = C.[TableId]
END
Based on the schema you can probably understand what I am trying to build.
My question is how do I order the result based on dynamic name
example (order by "StudentName" DESC)
Expected output
KeyValue ColumnId Value TableName ColumnName Order Key
'StudentName' 1 'Student Cathy' 'Student' 'StudentName' 1 1
'StudentName' 1 'Student Ben' 'Student' 'StudentName' 2 1
'StudentName' 1 'Student Alfonso' 'Student' 'StudentName' 3 1
'StudentName' 1 'Student Alex' 'Student' 'StudentName' 4 1
'StudentName' 1 'Student Alan' 'Student' 'StudentName' 5 1
'Grade' 2 '99' 'Student' 'Grade' 5 0 (Alan's Grade)
'Grade' 2 '98' 'Student' 'Grade' 4 0
... Year
... Section
...
How Do I sort by StudentName or Grade or Section or Year if key = student name
or
Sort by TeacherName or department if key = Teachername
indicated by #sortColumn NVARCHAR(20),
example
declare #SearchTerm NVARCHAR(max)=''
declare #pageNumber INT = 1
declare #pageSize INT = 10
declare #sortColumn NVARCHAR(20) ='StudentName'
declare #sortDirection int= 1 -- 0 asc 1 desc
exec [usp_DynamicSearch_Paged] #SearchTerm, #pageNumber, #pageSize, #sortColumn, #sortDirection

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

Return opposite transaction value rows

I have this table structure and I want a query that needs to be returning opposite side columns values.
CREATE TABLE TransactionDetail
(
ID NUMERIC NOT NULL PRIMARY KEY,
TransactionCode bigint,
COATitle NVARCHAR(50),
DrAmount NUMERIC,
CrAmount NUMERIC
);
INSERT INTO TransactionDetail VALUES (1, 1, 'Overtime', '2500', NULL);
INSERT INTO TransactionDetail VALUES (2, 1, 'Internship', NULL, '1500');
INSERT INTO TransactionDetail VALUES (3, 1, 'Medical', NULL, '1000');
INSERT INTO TransactionDetail VALUES (4, 2, 'Internship', '1150', NULL);
INSERT INTO TransactionDetail VALUES (5, 2, 'Overtime', NULL, '1150');
INSERT INTO TransactionDetail VALUES (6, 3, 'Overtime', '600', NULL);
INSERT INTO TransactionDetail VALUES (7, 3, 'Refreshment', '400', NULL);
INSERT INTO TransactionDetail VALUES (8, 3, 'Car Loan', '200', NULL);
INSERT INTO TransactionDetail VALUES (9, 3, 'Office Expenses', NULL, '1200');
If I pass parameter with value Overtime then it should return following rows
SELECT COATitle, DrAmount, CrAmount
FROM TransactionDetail
WHERE COATitle <> Overtime
Internship NULL 1500
Medical NULL 1000
Internship 1150 NULL
Office Expenses NULL 1200
The logic is against each transaction if the selected Account is on Debit side it should print the Credit side accounts and if the selected Account is on Credit side it should print Debit side accounts against that specific TransactionCode
The following code gives the desired result. It does that by checking to see whether the provided parameter is a debit or credit (or doesn't exist) in the current transaction, then only displays the reverse as specified.
declare #Parameter nvarchar(50) = 'Overtime'
declare #Trans TABLE
(
ID NUMERIC NOT NULL,
TransactionCode bigint,
COATitle NVARCHAR(50),
DrAmount NUMERIC,
CrAmount NUMERIC
);
INSERT INTO #Trans VALUES (1, 1, 'Overtime', '2500', NULL);
INSERT INTO #Trans VALUES (2, 1, 'Internship', NULL, '1500');
INSERT INTO #Trans VALUES (3, 1, 'Medical', NULL, '1000');
INSERT INTO #Trans VALUES (4, 2, 'Internship', '1150', NULL);
INSERT INTO #Trans VALUES (5, 2, 'Overtime', NULL, '1150');
INSERT INTO #Trans VALUES (6, 3, 'Overtime', '600', NULL);
INSERT INTO #Trans VALUES (7, 3, 'Refreshment', '400', NULL);
INSERT INTO #Trans VALUES (8, 3, 'Car Loan', '200', NULL);
INSERT INTO #Trans VALUES (9, 3, 'Office Expenses', NULL, '1200');
select TransactionCode, COATitle, DrAmount, CrAmount
from (
SELECT TransactionCode, COATitle, DrAmount, CrAmount
, case when exists (select 1 from #Trans T1 where T1.TransactionCode = T.TransactionCode and T1.COATitle = #Parameter and DrAmount is not null) then 1
when exists (select 1 from #Trans T1 where T1.TransactionCode = T.TransactionCode and T1.COATitle = #Parameter and CrAmount is not null) then -1
else 0 end TransSign
FROM #Trans T
WHERE COATitle <> #Parameter
) X
where (TransSign = -1 and DrAmount is not null)
or (TransSign = 1 and CrAmount is not null)

MINIMUM on second column, take first and third

DECLARE #Foo TABLE (Id INT, PozId INT, Val INT)
INSERT #Foo (Id, PozId, Val)
VALUES
(1, 1, 34),
(1, 2, 976),
(2, 1, 235),
(2, 2, 792),
(3, 2, 456),
(3, 3, 123)
How to get results like this from above query?
(1, 1, 34)
(2, 1, 235)
(3, 2, 456)
This brings you desired result. Query partitions your Ids and picks lowest PozitionId.
DECLARE #Foo TABLE
(
Id INT, PozId INT, Val INT
);
INSERT #Foo
(Id, PozId, Val)
VALUES
(1, 1, 34)
, (1, 2, 976)
, (2, 1, 235)
, (2, 2, 792)
, (3, 2, 456)
, (3, 3, 123);
SELECT Id, PozId, Val
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY Id ORDER BY PozId) AS RowNo, *
FROM #Foo
) AS T
WHERE RowNo = 1;

SQL merging tables [duplicate]

This question already has answers here:
Efficiently convert rows to columns in sql server
(5 answers)
Closed 8 years ago.
I am trying to merge a few tables in order to get the output as outlined in the image below.
My issue is that I am not sure what type of joins to use to achieve that
Can someone please help me with the syntax.
You could do something like this, it's a dynamic pivot as you might add/ take away users?
CREATE TABLE #Tests (
Test_ID INT,
TestName VARCHAR(50));
INSERT INTO #Tests VALUES (1, 'SQL Test');
INSERT INTO #Tests VALUES (2, 'C# Test');
INSERT INTO #Tests VALUES (3, 'Java Test');
CREATE TABLE #Users (
[User_ID] INT,
UserName VARCHAR(50));
INSERT INTO #Users VALUES (1, 'Joe');
INSERT INTO #Users VALUES (2, 'Jack');
INSERT INTO #Users VALUES (3, 'Jane');
CREATE TABLE #UserTests (
ID INT,
[User_ID] INT,
Test_ID INT,
Completed INT);
INSERT INTO #UserTests VALUES (1, 1, 1, 0);
INSERT INTO #UserTests VALUES (2, 1, 2, 1);
INSERT INTO #UserTests VALUES (3, 1, 3, 1);
INSERT INTO #UserTests VALUES (4, 2, 1, 0);
INSERT INTO #UserTests VALUES (5, 2, 2, 0);
INSERT INTO #UserTests VALUES (6, 2, 3, 0);
INSERT INTO #UserTests VALUES (7, 3, 1, 1);
INSERT INTO #UserTests VALUES (8, 3, 2, 1);
INSERT INTO #UserTests VALUES (9, 3, 3, 1);
DECLARE #Cols VARCHAR(MAX);
SELECT #Cols = STUFF((SELECT distinct ',' + QUOTENAME(u.UserName)
FROM #Users u
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
DECLARE #Query NVARCHAR(MAX);
SELECT #Query = 'SELECT TestName, ' + #Cols + ' FROM
(
SELECT
t.TestName,
u.UserName,
ut.Completed
FROM
#Tests t
INNER JOIN #UserTests ut ON ut.Test_ID = t.Test_ID
INNER JOIN #Users u ON u.[User_ID] = ut.[User_ID]) x
PIVOT (
MAX(Completed)
FOR UserName IN (' + #Cols + ')
) AS pt';
EXEC(#Query);
Results are:
TestName Jack Jane Joe
C# Test 0 1 1
Java Test 0 1 1
SQL Test 0 1 0
(Same results as yours, but in a different sort order.)