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/
Related
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
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
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
The below code demonstrates the problem I'm trying to solve. Basically I only want to select transactions where a customer has never purchased a product where isActive is now 0.
I tried using GROUP BY and HAVING MIN(p.isActive) = 1 to get only the customers associated with active products. This query is close but MIN does not like bit type. How can I do this?
The goal is to only see transactions associated with just Lisa and Fred. Bill should be removed from the results since one of his transactions is currently associated with a InActive product.
CustomerName ProductName (No column name)
Bill Cheerios 1
Lisa Cheerios 1
Bill Corn Flakes 1
Fred Corn Flakes 1
Bill Granola 0
ERROR: Operand data type bit is invalid for min operator.
CREATE TABLE #Customer (
CustomerId int,
CustomerName nvarchar(100),
Address nvarchar(100),
)
INSERT INTO #Customer
VALUES (1, 'Bill', '123 1st St'),
(2, 'Fred', '111 Market St'),
(3, 'Lisa', '01 Boulevard')
CREATE TABLE #Product (
ProductId int,
ProductName nvarchar(100),
isActive bit
)
INSERT INTO #Product
VALUES (1, 'Corn Flakes', 1),
(2, 'Cheerios', 1),
(3, 'Granola', 0)
CREATE TABLE #TransactionLog (
LogId int,
ProductId int,
CustomerId int,
Amount float
)
INSERT INTO #TransactionLog
VALUES (1, 1, 1, 2.00),
(2, 2, 1, 2.40),
(3, 3, 1, 1.80),
(4, 1, 1, 2.00),
(5, 1, 2, 2.00),
(6, 2, 3, 2.40)
SELECT * from #Customer
SELECT * from #Product
SELECT * from #TransactionLog
SELECT
c.CustomerName,
p.ProductName,
MIN(p.isActive)
FROM #TransactionLog t
join #Product p on t.ProductId = p.ProductId
join #Customer c on t.CustomerId = c.CustomerId
GROUP BY
c.CustomerName,
p.ProductName
HAVING
MIN(p.isActive) = 1
DROP TABLE #Customer
DROP TABLE #Product
DROP TABLE #TransactionLog
I'm not sure why but when I try HAVING MIN(CAST(p.isActive AS INT)) = 1, I still get 2 rows of data associated with Bill. I'd like to eliminate Bill from the result.
Bill Cheerios 1
Lisa Cheerios 1
Bill Corn Flakes 1
Fred Corn Flakes 1
with data as (
SELECT
c.CustomerName, p.ProductName,
count(case when p.isActive = 0 then 1 end)
over (partition by c.CustomerID) as countInactive
FROM #TransactionLog t
inner join #Product p on t.ProductId = p.ProductId
inner join #Customer c on t.CustomerId = c.CustomerId
)
select * from data where countInactive = 0;
You can accomplish it with min() over () as well if you prefer that logic.
You can always convert to a number:
HAVING MIN(CONVERT(tinyint, p.isActive)) = 1
This works for me - casting to INT as suggested in my comment:
CREATE TABLE #Customer (
CustomerId int,
CustomerName nvarchar(100),
Address nvarchar(100),
)
INSERT INTO #Customer
VALUES (1, 'Bill', '123 1st St'),
(2, 'Fred', '111 Market St'),
(3, 'Lisa', '01 Boulevard')
CREATE TABLE #Product (
ProductId int,
ProductName nvarchar(100),
isActive bit
)
INSERT INTO #Product
VALUES (1, 'Corn Flakes', 1),
(2, 'Cheerios', 1),
(3, 'Granoloa', 0)
CREATE TABLE #TransactionLog (
LogId int,
ProductId int,
CustomerId int,
Amount float
)
INSERT INTO #TransactionLog
VALUES (1, 1, 1, 2.00),
(2, 2, 1, 2.40),
(3, 3, 1, 1.80),
(4, 1, 1, 2.00),
(5, 1, 2, 2.00),
(6, 2, 3, 2.40)
SELECT * from #Customer
SELECT * from #Product
SELECT * from #TransactionLog
SELECT
c.CustomerName,
p.ProductName,
MIN(CAST(p.isActive AS int))
FROM #TransactionLog t
join #Product p on t.ProductId = p.ProductId
join #Customer c on t.CustomerId = c.CustomerId
GROUP BY
c.CustomerName,
p.ProductName
HAVING
MIN(CAST(p.isActive AS INT)) = 1
DROP TABLE #Customer
DROP TABLE #Product
DROP TABLE #TransactionLog
I would propose a join instead:
CREATE TABLE #Customer (
CustomerId int,
CustomerName nvarchar(100),
Address nvarchar(100),
)
INSERT INTO #Customer ( CustomerId, CustomerName, Address )
VALUES (1, 'Bill', '123 1st St'),
(2, 'Fred', '111 Market St'),
(3, 'Lisa', '01 Boulevard')
CREATE TABLE #Product (
ProductId int,
ProductName nvarchar(100),
isActive bit
)
INSERT INTO #Product (ProductId, ProductName, isActive)
VALUES (1, 'Corn Flakes', 1),
(2, 'Cheerios', 1),
(3, 'Granoloa', 0)
CREATE TABLE #TransactionLog (
LogId int,
ProductId int,
CustomerId int,
Amount float
)
INSERT INTO #TransactionLog (LogId, ProductId ,CustomerId ,Amount )
VALUES (1, 1, 1, 2.00),
(2, 2, 1, 2.40),
(3, 3, 1, 1.80),
(4, 1, 1, 2.00),
(5, 1, 2, 2.00),
(6, 2, 3, 2.40)
--SELECT * from #Customer
--SELECT * from #Product
--SELECT * from #TransactionLog
SELECT
c.CustomerName,
p.ProductName,
p.isActive
FROM #TransactionLog t
INNER JOIN #Product p on t.ProductId = p.ProductId AND p.isActive = 1
INNER JOIN #Customer c on t.CustomerId = c.CustomerId
GROUP BY
c.CustomerName,
p.ProductName
DROP TABLE #Customer
DROP TABLE #Product
DROP TABLE #TransactionLog
EDIT: PER NOTE, Get rid of Bill if he every ordered an inactive product
CREATE TABLE #Customer (
CustomerId int,
CustomerName nvarchar(100),
Address nvarchar(100),
)
INSERT INTO #Customer ( CustomerId, CustomerName, Address )
VALUES (1, 'Bill', '123 1st St'),
(2, 'Fred', '111 Market St'),
(3, 'Lisa', '01 Boulevard')
CREATE TABLE #Product (
ProductId int,
ProductName nvarchar(100),
isActive bit
)
INSERT INTO #Product (ProductId, ProductName, isActive)
VALUES (1, 'Corn Flakes', 1),
(2, 'Cheerios', 1),
(3, 'Granoloa', 0)
CREATE TABLE #TransactionLog (
LogId int,
ProductId int,
CustomerId int,
Amount float
)
INSERT INTO #TransactionLog (LogId, ProductId ,CustomerId ,Amount )
VALUES (1, 1, 1, 2.00),
(2, 2, 1, 2.40),
(3, 3, 1, 1.80),
(4, 1, 1, 2.00),
(5, 1, 2, 2.00),
(6, 2, 3, 2.40)
--SELECT * from #Customer
--SELECT * from #Product
--SELECT * from #TransactionLog
SELECT
c.CustomerName,
p.ProductName,
p.isActive
FROM #TransactionLog AS t
INNER JOIN #Product AS p on t.ProductId = p.ProductId
AND NOT EXISTS (
SELECT 1
FROM #TransactionLog AS ts
INNER JOIN #Product AS ps
ON ts.ProductId = ps.ProductId
AND ps.isActive = 0
WHERE ts.CustomerId = t.CustomerId
)
INNER JOIN #Customer c on t.CustomerId = c.CustomerId
GROUP BY
c.CustomerName,
p.ProductName,
p.isActive
DROP TABLE #Customer
DROP TABLE #Product
DROP TABLE #TransactionLog
I am using two query from a schema which counts companies, but I am struggling how to combine them give Columns as Country and Industry as row and give the company counts accordingly.
select g.simpleindustrydescription, count(c.companyid) as companycount from ciqcompany c
join ciqsimpleindustry g on g.simpleIndustryid = c.simpleIndustryid
join ciqbusinessdescription b on b.companyid = c.companyid
group by g.simpleindustrydescription
select g.country, count(c.companyid) as companycount from ciqcompany c
join ciqcountrygeo g on g.countryid = c.countryid
join ciqbusinessdescription b on b.companyid = c.companyid
group by g.country
Expected Output:
Country A Country B Country C
Industry A 5 5 6
Industry B 3 3 4
Industry C 4 8 6
Due to lack of real example data, here a simple pivot example basing on some dummy records:
CREATE TABLE #tCountry
(
ID INT
,Name NVARCHAR(100)
);
INSERT INTO #tCountry VALUES (1, 'Country A'), (2, 'Country B'), (3, 'Country C');
CREATE TABLE #tIndustry
(
ID INT
,Name NVARCHAR(100)
);
INSERT INTO #tIndustry VALUES (1, 'Industry A'), (2, 'Industry B'), (3, 'Industry C');
CREATE TABLE #tMapping
(
ID INT
,CountryID INT
,IndustryID INT
,Name NVARCHAR(100)
);
INSERT INTO #tMapping VALUES (1, 1, 1, 'Country A Industry A - 1'), (2, 1, 1, 'Country A Industry A - 2');
INSERT INTO #tMapping VALUES (3, 1, 2, 'Country A Industry B - 1'), (4, 1, 2, 'Country A Industry b - 2'), (5, 1, 2, 'Country A Industry b - 3');
INSERT INTO #tMapping VALUES (6, 2, 1, 'Country B Industry A - 1');
DECLARE #lCountries NVARCHAR(max) = N'';
DECLARE #stmt NVARCHAR(MAX) = N'';
SELECT #lCountries += N', ' + QUOTENAME(CountryName)
FROM(
SELECT DISTINCT tc.Name CountryName
FROM #tCountry tc
JOIN #tMapping tm ON tm.CountryID = tc.ID
) x;
SELECT #lCountries = STUFF(#lCountries, 1, 2, '');
SELECT #stmt = 'SELECT *
FROM
(
SELECT ti.Name IndustryName, tc.Name CountryName, COUNT(*) MappingCounter
FROM #tMapping tm
JOIN #tCountry tc ON tm.CountryID = tc.ID
JOIN #tIndustry ti ON tm.IndustryID = ti.ID
GROUP BY ti.Name, tc.Name
) t
PIVOT (MAX(t.MappingCounter) FOR CountryName in (' + #lCountries + ')) AS x';
EXEC sp_executesql #stmt
Anyways, if you are dealing with an unknown number of countries, you might want to extend this example a little and use dynamic SQL in order to build the pivot statement. Got an example somewhere, but would have to search for it...
Result of my example:
IndustryName Country A Country B Country C
Industry A 2 1 NULL
Industry B 3 NULL NULL