How to get this using PIVOT? - sql-server

I have a table something like this:-
DATE AREA
01-01-2018 AREA-1
02-01-2018 AREA-1
03-01-2018 AREA-2
My Desired Result should be something like this:-
AREA 01-01-2018 02-01-2018 03-01-2018
AREA-1 YES YES NO
AREA-2 NO NO YES
How can I get this?

Here is one way using Pivot
SELECT AREA,
COALESCE([01-01-2018], 'NO'),
COALESCE([02-01-2018], 'NO'),
COALESCE([03-01-2018], 'NO')
FROM (SELECT *,
'YES' AS t
FROM Yourtable)a
PIVOT(Max(t)
FOR DATE IN ([01-01-2018],[02-01-2018],[03-01-2018]) ) pv
Even easier method
SELECT AREA,
Max(CASE WHEN date = '01-01-2018' THEN 'YES' ELSE 'NO' END),
Max(CASE WHEN date = '02-01-2018' THEN 'YES' ELSE 'NO' END),
Max(CASE WHEN date = '03-01-2018' THEN 'YES' ELSE 'NO' END)
FROM Yourtable
GROUP BY AREA
Dynamic version
DECLARE #col_list VARCHAR(max)='',
#select_list VARCHAR(max)='',
#sql VARCHAR(max)
SET #col_list = Stuff((SELECT DISTINCT ',' + Quotename(DATE)
FROM Yourtable
FOR xml path('')), 1, 1, '')
SET #select_list = Stuff((SELECT DISTINCT ',COALESCE(' + Quotename(DATE) + ',''NO'') as ' + Quotename(DATE)
FROM Yourtable
FOR xml path('')), 1, 1, '')
SET #sql = '
SELECT AREA,' + #select_list + '
FROM (SELECT *,
''YES'' AS t
FROM Yourtable)a
PIVOT(Max(t)
FOR DATE IN (' + #col_list + ') ) pv'
EXEC (#sql)
Note : Always store dates in Date type instead of varchar

Related

Optimise a Stored procedure in SQL? Facing Error

Can someone help me to optimise this SP as it takes more than 3 minutes to run and then it gives Timeout error. "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." I am a beginner and would like to optimise the below SP because it takes forever to give results and it also gives timeout error. I tried putting indexing to temp tables but unsuccessful. Help !!!!
ALTER PROCEDURE GetCompanyByCandidatetest
#USER_ID VARCHAR(50) = NULL
AS
BEGIN
declare #statenew varchar(1000) = Null
declare #countnew varchar(1000) = Null
declare #STRSQLNew varchar(max)
declare #STRSQL4 varchar(max)
declare #state1 varchar(1000) = Null ,#ind varchar(1000) = Null,#Distinct varchar(1000) = Null,#Dist1 varchar(1000) = Null,
#EQuit_ID varchar(1000) = Null,#Degree_ID varchar(100) = Null,#Isguest varchar(100) = Null,#verified varchar(100) = Null,
#keyword varchar(100) = Null,#workexperience varchar(100) = Null,#prefcity varchar(100) = Null,#addcity varchar(100) = Null,
#Key_skill varchar(100) = Null,#CURRENT_DEPARTMENT varchar(100),#PREF_DEPARTMENT varchar(100),#CURRENT_DESIGNATION varchar(100),#PREF_DESIGNATION varchar(100),#indcurr varchar(100)
select #Isguest = isnull(guest_login,0), #verified = isnull(VERIFIED,0) from mtb_frinds where user_id = #USER_ID
select #statenew = isnull(PREF_STATE,''),#state1 = isnull(ADD_STATE,''),#Distinct = isnull(PREF_DISTRICT,''),#Distinct1 = isnull(add_dist,''),
#ind = isnull(PREF_INDUSTRY,''),#indcurr=isnull(CURRENT_INDUSTRY,'') ,#EQuit_ID = isnull(EQ_ID,'') ,#keyword=isnull(key_word,'') ,#workexperience=isnull(WORK_EXPYEARS,''),#CURRENT_DEPARTMENT=isnull(CURRENT_DEPARTMENT,''), #PREF_DEPARTMENT=isnull(PREF_DEPARTMENT,''),
#prefcity=isnull(PREF_CITY,'') ,#addcity=ADD_CITY,#Key_skill=isnull(Key_skill,''),#CURRENT_DESIGNATION=isnull(CURRENT_DESIGNATION,''),#PREF_DESIGNATION=isnull(PREF_DESIGNATION,'')
from mtb_frinds where USER_ID = #USER_ID
if(#statenew!='' and #Key_skill !='' and #state1 !='' and #keyword !='' )
begin
print 'ind' +#ind
print '#indcurr' +#indcurr
print '#PREF_DEPARTMENT'+ #PREF_DEPARTMENT
print '#CURRENT_DEPARTMENT'+#CURRENT_DEPARTMENT
print '#keyword'+ #keyword
set #STRSQLNew='
select ej_id, EQ_ID, JOB_STATUS ,job_desc,
active, USER_ID, JOB_TITLE, CREATED_ON,
REQUIRED_MP, WORK_EXPYEARS, SALARY, IND_ID,
Key_skill, STATE_ID, DIST_ID, LOCALITY_ID,
DEPT_ID,1 as Priority, EXPIRATION_DATE
into #dummy from mtb_jobs Ek
'
IF #EQuit_ID IS NOT NULL AND #EQuit_ID != ''
BEGIN
print 1
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(EQ_ID,'','') AS A
CROSS APPLY dbo.Split('''+#EQuit_ID+''','','') AS B'
set #STRSQL4 ='(((A.items = B.items) or '
END
IF #keyword IS NOT NULL AND #keyword != ''
BEGIN
print 2
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(keywords,'','') AS e
CROSS APPLY dbo.Split('''+#keyword+''','','') AS f'
set #STRSQL4 =#STRSQL4+'(e.items =f.items)) and '
END
IF #statenew IS NOT NULL AND #statenew != ''
BEGIN
print 3
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS i
CROSS APPLY dbo.Split('''+#statenew+''','','') AS j'
set #STRSQL4 = #STRSQL4+'((i.items =j.items) '
END
IF #state1 IS NOT NULL AND #state1 != ''
BEGIN
print 4
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS k
CROSS APPLY dbo.Split('''+#state1+''','','') AS l'
set #STRSQL4 =#STRSQL4+' or (k.items =l.items)) and '
END
IF #Key_skill IS NOT NULL AND #Key_skill != ''
BEGIN
print 5
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(Key_skill,'','') AS g
CROSS APPLY dbo.Split('''+#Key_skill+''','','') AS h'
set #STRSQL4 =#STRSQL4+' ((g.items =h.items) or
'
END
set #STRSQLNew = #STRSQLNew+ ' where '+ #STRSQL4 +'(DEPT_ID in (select items from dbo.split('''+#CURRENT_DEPARTMENT+''','','')) or DEPT_ID in (select items from dbo.split('''+#PREF_DEPARTMENT+''','','')))))
or(e.items =f.items and ((k.items =l.items) or (i.items =j.items) ))
'
set #STRSQLNew =#STRSQLNew+ ' select * into #temp from ( select max(ej_id) as ej_id , max(EQ_ID) as EQ_ID, max(JOB_STATUS) as JOB_STATUS , max(job_desc) as job_desc,max(active) as active, max(USER_ID) as USER_ID ,max(JOB_TITLE) as JOB_TITLE ,max(CREATED_ON) as CREATED_ON ,max(REQUIRED_MP) as REQUIRED_MP ,max(WORK_EXPYEARS) as WORK_EXPYEARS ,
max(SALARY) as SALARY ,max(IND_ID) as IND_ID ,max(Key_skill) as Key_skill , max(STATE_ID) as STATE_ID ,max(DIST_ID) as DIST_ID,max(LOCALITY_ID) as LOCALITY_ID ,max(DEPT_ID) as DEPT_ID,2 as Priority,max(EXPIRATION_DATE) as EXPIRATION_DATE from #dummy where EXPIRATION_DATE >0 group by ej_id
) as x '
set #STRSQLNew =#STRSQLNew+' select * into #Temp2 from
(
select a.ej_id, isnull(a.JOB_TITLE,'''') as JOB_TITLE, isnull(b.ENT_NAME,'''') as ENT_NAME, CASE
WHEN DATEDIFF(SECOND, a.CREATED_ON, GETDATE()) < 60 THEN ''Just Posted''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 60 THEN CAST(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) AS VARCHAR(10)) + '' Minutes ago''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 24 * 60 THEN CAST(FLOOR(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE())/60) AS VARCHAR(10)) + '' Hours ago''
ELSE CAST(FLOOR(DATEDIFF(HOUR, a.CREATED_ON, GETDATE())/24) AS VARCHAR(10)) + ''Days ago''
END AS POSTED_ON,a.REQUIRED_MP,''1'' as Issuitable,a.job_desc, a.created_on,DATEDIFF(DAY,GETDATE(),a.EXPIRATION_DATE) as EXPIRATION_DATE
,isnull('''+#Isguest+''',''0'') as Isguest,isnull('''+#verified+''',''0'') as Isverified
,isnull(cnt,0) as Isapplied,substring(
(
Select distinct '', ''+ ST1.StateName AS [text()]
From MTB_STATESNEW ST1
Where ST1.StateId in (select items from dbo.split (a.state_id,'',''))
For XML PATH ('''')
), 2, 1000000) [StateName],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.MIN_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [min_exp],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.MAX_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [max_exp],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.SR_MIN)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select min(items) from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [min_Salary],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.sr_max)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select items from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [max_Salary],
substring(
(
Select distinct '',''+ (convert(varchar(1000),ST1.KEY_SKILL)) AS [text()]
From MTB_KEYSKILL ST1
Where ST1.KEYSKILL_ID in (select items from dbo.split (a.Key_skill,'',''))
For XML PATH ('''')
), 2, 1000000) [KEY_SKILL]
,
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.KEYWORDS)) AS [text()]
From mtb_keywords ST1 where st1.KEYWORD_ID in ( select items from dbo.split('''+#keyword+''','',''))
For XML PATH ('''')
), 2, 1000000) [KEY_Word],
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.DIST_NAME)) AS [text()]
From MTB_DISTSNEW ST1 where st1.DIST_ID in ( select items from dbo.split(a.DIST_ID,'',''))
For XML PATH ('''')
), 2, 1000000) [dist_name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.EQ_NAME)) as [text()]
from MTB_EDUQUALIFICATIONS ST1 where st1.EQ_ID in (select items from dbo.split(a.EQ_ID,'',''))
For XML PATH('''')
),2,1000000) [EQ_Name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.IND_NAME)) as [text()]
from mtb_industry ST1 where st1.ind_id in (select items from dbo.split(a.ind_id,'',''))
For XML PATH('''')
),2,1000000) [IND_NAME]
from #temp as a inner join MTB_ENTERPRISES as b on a.user_id = b.user_id
left join (select count (ej_id) as cnt,ej_id from TTB_JOBAPPLICATIONS where USER_ID = '''+#USER_ID+''' group by EJ_ID) as ER on ER.EJ_ID = a.EJ_ID
where( a.JOB_STATUS = 1 and a.active = 1 )
) as x'
set #STRSQLNew =#STRSQLNew+' SELECT *,isnull(min_exp,'''') +''-''+ isnull(max_exp,'''') as WORK_EXP,isnull(min_Salary,'''') +''-''+ isnull(max_salary,'''') as Salary FROM #Temp2 '
print #STRSQLNew
exec (#STRSQLNew)
select 1 as ispara1, 'Sucess' as Msg ,1 as n
end
else
begin
select top 0* from MTB_ENTERPRISES
select 0 as ispara2, 0 as n,'Some fields are Incomplete' as Msg
end
END
Error:- Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Concatenate columns of multiple columns and multiple rows into one varchar value, when no of columns is dynamic

So i have this dynamic query that returns a result set having dynamic number of columns like so:
In this result set we have columns for ID, FacilityName and cycleNum will always be there but number of task columns can vary Task1, Task2, Task3..... upto Taskn.
The final result set I need is as follows:
For this i have tried this query:
Select distinct FacilityName,
substring(
(
Select ',' + a
From (SELECT ID, FacilityName, 'Cycle-'+ cast(CycleNum as varchar)+'::' + 'Task1~' + cast(Task1 as varchar) + ',Task2~' + cast(Task2 as varchar) + ',Task3~' + cast(Task3 as varchar) + ';' as a FROM #tempTable) ST1
Where ST1.FacilityName = ST2.FacilityName
ORDER BY ST1.FacilityName
For XML PATH ('')
), 2, 1000) CycleData
From (SELECT ID, FacilityName, 'Cycle-'+ cast(CycleNum as varchar)+'::' + 'Task1~' + cast(Task1 as varchar) + ',Task2~' + cast(Task2 as varchar) + ',Task3~' + cast(Task3 as varchar)+ ';' as a FROM #tempTable) ST2
This will work with following test data:
create table #tempTable
(
ID int,
FacilityName varchar(50),
CycleNum int,
Task1 datetime,
Task2 datetime,
Task3 datetime
)
Insert into #tempTable values
(1, 'A', 1, convert(varchar(10), getdate(), 126), convert(varchar(10), dateadd(day,1,getdate()), 126), convert(varchar(10), dateadd(day,2,getdate()), 126)),
(2, 'A', 2, convert(varchar(10), getdate(), 126), convert(varchar(10), dateadd(day,1,getdate()), 126), convert(varchar(10), dateadd(day,2,getdate()), 126)),
(3, 'B', 1, convert(varchar(10), getdate(), 126), convert(varchar(10), dateadd(day,1,getdate()), 126), convert(varchar(10), dateadd(day,2,getdate()), 126)),
(4, 'B', 2, convert(varchar(10), getdate(), 126), convert(varchar(10), dateadd(day,1,getdate()), 126), convert(varchar(10), dateadd(day,2,getdate()), 126))
But I cant think of any way to extend this to use dynamic columns. The list of all columns is saved in a master table so we can get comma-separated list of columns from there if needed.
Here is a dynamic way
Slightly different approach from your static query. To make it dynamic, Use while loop or CURSOR to generate the Task1 + Task2 + ..TaskN. Then use it in Select query.
DECLARE #columns VARCHAR(50)='Task1,Task2,Task3', -- Pass the list of column names
#int INT = 1,
#sql VARCHAR(8000)
SET #sql = ' ;WITH cte
AS (SELECT *,
''Cycle-'' + Cast(CycleNum AS VARCHAR(10)) + ''::'' '
WHILE #int <= Len(#columns) - Len(Replace(#columns, ',', '')) -- To find the number of Tasks in list
BEGIN
SET #sql += + '+''Task' + Cast(#int AS VARCHAR(10))
+ '~''+' + 'Cast(Task'
+ Cast(#int AS VARCHAR(10))
+ ' AS VARCHAR(50)) + '','''
SET #int += 1
END
SET #sql += ' AS concat_dates
FROM #tempTable)
SELECT DISTINCT FacilityName,
LEFT(CycleData, Len(CycleData) - 1)
FROM cte a
CROSS apply(SELECT b.concat_dates + '',''
FROM cte b
WHERE a.FacilityName = b.FacilityName
FOR xml path('''')) cs (CycleData)
'
--print #sql -- uncomment it to debug if you have any error when executing dynamic code
EXEC (#sql)
Not to worry about the usage of While Loop/CURSOR since we are not doing any resource intensive operations inside the loop.
Static Query will looking like this
;WITH cte
AS (SELECT *,
'Cycle-' + Cast(CycleNum AS VARCHAR(10))
+ '::' + 'Task1~' + Cast(Task1 AS VARCHAR(50))
+ ',' + 'Task2~' + Cast(Task2 AS VARCHAR(50))
+ ',' AS concat_dates
FROM #tempTable)
SELECT DISTINCT FacilityName,
LEFT(CycleData, Len(CycleData) - 1)
FROM cte a
CROSS apply(SELECT b.concat_dates + ','
FROM cte b
WHERE a.FacilityName = b.FacilityName
FOR xml path('')) cs (CycleData)
Use system tables. I prefer short and effective solutions :). This is guide, I'm sure you can finish it yourself with concentating strings (if you are not sure, add comment and I will add whole code or more description).
declare #columns varchar(max)
SELECT #columns = isnull(#columns + '+', '') + '''' + COLUMN_NAME + '~'' + Cast(' + COLUMN_NAME + ' as varchar(50))'
FROM tempdb.INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME like '#tempTable%'
AND c.COLUMN_NAME LIKE 'Task%' -- filter columns you are interested in
declare #sql varchar(4000) = 'select *, ' + #columns + ' from #tempTable'
print #sql
exec (#sql)

SQL Server Row Into Column

We have a table showing amounts (CHGCNT) for 3 dates (5-9-2016, 5-10-2016, 5-11-2016) for each store & Depts.
I want to be able to see the records in a table like this:
I already applied the following query
declare #dt as datetime
declare #dt1 as varchar(10)
declare #dt2 as varchar(10)
declare #dt3 as varchar(10)
select distinct #dt = min(effdt) from [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
-- print CONVERT(CHAR(10), #dt, 110) + ' ---- ' + CONVERT(CHAR(10), #dt+1 , 110)
set #dt1 = CONVERT(CHAR(10), #dt, 110)
set #dt2 = CONVERT(CHAR(10), #dt +1 , 110)
set #dt3 = CONVERT(CHAR(10), #dt + 2 , 110)
--print #dt1 + ' ---- ' + #dt2 + '-----' + #dt3
SELECT DEPTNM, DEPT, [#dt1] , [#dt2] , [#dt3]
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
PIVOT
(
SUM(CHGCNT)
FOR effdt IN ( [#dt1] , [#dt2] , [#dt3])
) AS P
but it is returning dates
I like the SUM-CASE approach:
SELECT deptnm,
SUM(CASE WHEN effdt = '2016-05-09' THEN chgcnt ELSE 0 END) "2016-05-09",
SUM(CASE WHEN effdt = '2016-05-10' THEN chgcnt ELSE 0 END) "2016-05-10",
SUM(CASE WHEN effdt = '2016-05-11' THEN chgcnt ELSE 0 END) "2016-05-11",
SUM(effdt) Total
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
GROUP BY deptnm;

Count non-empty rows with unknown column names

Given a table that has unknown column names, how can I list all column names and the amount of rows that have a non-empty (NULL or empty string) value in that column?
Small example:
Col1 | Col2 | Col3 | dkasldk | dD? d3# !(
1 | | 2 | |
| 2 | d | ddd939 |
f | f | 84 | |
Should yield:
Column Name | Values
Col1 | 2
Col2 | 2
Col3 | 3
dkasldk | 1
dD? d3# !( | 0
I already tried around with using INFORMATION_SCHEMA.COLUMNS and creating dynamic SQL queries, but to no avail:
select N'select c.COLUMN_NAME,
(select sum(case when p.' + QUOTENAME(c.COLUMN_NAME) + ' != '''' then 1 else 0 end) from [Produkte] p) [Produkte]
from INFORMATION_SCHEMA.COLUMNS c
where c.TABLE_NAME = ''Produkte'' and c.COLUMN_NAME = ''' + c.COLUMN_NAME + '''' select_statement
from INFORMATION_SCHEMA.COLUMNS c
where c.TABLE_NAME = 'Produkte'
I cannot quite wrap my head around how to combine the two problems (for which I did find solution in their own, but not the combination) of Dynamic Column Names and Count empty values...
You can do something like this using UNPIVOT..
DECLARE #TableName NVARCHAR(MAX) = N'Produkte',
#CountColumns NVARCHAR(MAX),
#Columns NVARCHAR(MAX),
#Sql NVARCHAR(MAX)
SELECT #CountColumns = COALESCE(#CountColumns + ',', '') + 'COUNT(NULLIF(' + QUOTENAME(c.COLUMN_NAME) + ','''')) AS ' + QUOTENAME(c.COLUMN_NAME),
#Columns = COALESCE(#Columns + ',', '') + QUOTENAME(c.COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = #TableName
SET #SQL = 'SELECT [Column Name], [Values]
FROM (
SELECT '
+ #CountColumns + '
FROM ' + #TableName + '
) t
UNPIVOT (
[Values]
FOR [Column Name] IN (' + #Columns + ')
) up
'
EXEC(#SQL)
SQL Fiddle Demo
You can use a dynamic UNPIVOT.
Using these variables:
DECLARE #qry NVARCHAR(MAX)
DECLARE #cols NVARCHAR(MAX) = ''
you can select columns names in a format suitable for the UNPIVOT operation with the following dynamic sql:
SELECT #cols = STUFF((SELECT ',[' + c.COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = 'Produkte'
FOR XML PATH('')), 1, 1, '')
Finally use #cols to build the query:
SET #qry = 'SELECT t.Col, COUNT(*)
FROM (SELECT Val, Col
FROM Produkte
UNPIVOT (
Val FOR Col IN (' + #cols + ')) unpvt
) AS t
WHERE t.Val <> '''' OR t.Val IS NOT NULL
GROUP BY t.Col'
... and execute it to get desired result:
EXEC(#qry)
Ultimately the SQL you are after is something like this:
SELECT ColumnName, NonEmpty
FROM ( SELECT A = 1,
[Col1] = COUNT(CASE WHEN [Col1] <> '' THEN 1 END),
[Col2] = COUNT(CASE WHEN [Col2] <> '' THEN 1 END),
[Col3] = COUNT(CASE WHEN [Col3] <> '' THEN 1 END),
[dkasldk] = COUNT(CASE WHEN [dkasldk] <> '' THEN 1 END),
[dD? d3# !(] = COUNT(CASE WHEN [dD? d3# !(] <> '' THEN 1 END)
FROM #T
) AS t
UNPIVOT
( NonEmpty
FOR ColumnName IN ([Col1],[Col2],[Col3],[dkasldk],[dD? d3# !(])
) AS upvt;
UNPIVOT Will convert your data from
Col1 Col2 Col3
-------------------------
1 3 2
To the format you require:
ColumnName NonEmpty
-------------------------
Col1 1
Col2 3
Col3 2
You can build up dynamically using something like this:
-- SAMPLE DATA
USE TempDB;
CREATE TABLE #T
(
[Col1] VARCHAR(1),
[Col2] VARCHAR(1),
[Col3] VARCHAR(2),
[dkasldk] VARCHAR(6),
[dD? d3# !(] VARCHAR(1)
);
INSERT #T ([Col1], [Col2], [Col3], [dkasldk], [dD? d3# !(])
VALUES
('1', NULL, '2', NULL, ''),
('', '2', 'd', 'ddd939', NULL),
('f', 'f', '84', NULL, '');
DECLARE #TableName SYSNAME = '#T';
-- VALID INPUT TABLE
IF OBJECT_ID(#TableName, 'U') IS NULL
AND OBJECT_ID(#TableName, 'V') IS NULL
BEGIN
PRINT 'Invalid table or View';
RETURN
END
-- BUILD DYNAMIC SQL
DECLARE #SQL NVARCHAR(MAX) =
CONCAT('SELECT ColumnName, NonEmpty FROM (SELECT A = 1, ' ,
STUFF(( SELECT CONCAT(',',
QUOTENAME(name),
' = COUNT(CASE WHEN ',
QUOTENAME(Name),
' <> '''' THEN 1 END)')
FROM sys.columns
WHERE [object_id] = OBJECT_ID(#TableName)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
' FROM ',
#TableName,
') AS t UNPIVOT (NonEmpty FOR ColumnName IN (',
STUFF(( SELECT CONCAT(',', QUOTENAME(name))
FROM sys.columns
WHERE [object_id] = OBJECT_ID(#TableName)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
')) AS upvt');
-- EXECUTE DYNAMIC SQL
EXECUTE sp_executesql #SQL;

How to add DISTINCT to a column in select query

Can you help me how to use DISTINCT in this query?
DECLARE #ReadData NVARCHAR(MAX);
SET #ReadData = 'SELECT ROW_NUMBER() OVER (ORDER BY RM.ReceiverDate) AS [S. No.]
,DISTINCT RM.ReceiverId
,RM.ReceiverDateas [Receiver Date]
,VM.VendorName as [Vendor Name]
,VM.VendorID
FROM Receiver RM
LEFT OUTER JOIN VendorMaster VM on VM.VendorID = RM.VendorId
WHERE ['+ #ColumnName + '] LIKE
CASE WHEN ' + #Filter+ ' = 0 THEN ''%' + #Value + '%'''+
' WHEN ' + #Filter + ' = 1 THEN '''+ #Value + '%'''+
' WHEN ' + #Filter + ' = 2 THEN ''%' + #Value +''' END
AND VM.IsActive = 1
AND RM.VendorID = CASE WHEN ' + CONVERT(VARCHAR, #VendorID) + ' = ''-1'' THEN RM.VendorID
ELSE '+ CONVERT(VARCHAR, #VendorID) +' END
AND (RM.ReceiverDate BETWEEN ' + CHAR(39) + CONVERT(VARCHAR(23), #FromDate, 126) + CHAR(39) +' AND ' + CHAR(39) + CONVERT(VARCHAR(23), #ToDate, 126) + CHAR(39) +')
ORDER BY RM.ReceiverDate '
My question is: how to add DISTINCT to the ReceiverId ?
I get this error:
Incorrect syntax near the keyword 'DISTINCT'.
in the C# code behind
with cte
as
(
Select ROW_NUMBER() OVER (PARTITION BY ReceiverId ORDER BY ReceiverId ) AS dupCount, *
from(
SELECT ROW_NUMBER() OVER (ORDER BY ReceivedDate) AS [S. No.]
,RM.ReceiverId
,RM.ReceiverName'
,VM.VendorName
, XYZ columns .....
From Receiver RM
LEFT OUTER JOIN VendorMaster VM on VM.VendorID = RM.VendorId
) tab
)
select S. No.
,ReceiverId
,ReceiverName
,VendorName
, XYZ columns
from cte
where dupcount=1;
try using cte.
DECLARE #ReadData NVARCHAR(MAX);
set #ReadData = 'SELECT *
,ROW_NUMBER() OVER (ORDER BY ReceivedDate) AS [S. No.]
FROM (SELECT DISTINCT ReceiverId,
ReceivedDate
,ReceiverName
, XYZ columns .....
From Receiver .........
INNER JOIN .......)'
You can't use the row_number and distinct on same level.

Resources