Related
I am trying to pivot on multiple columns and have dynamic column names in the result. I am using SQL server 2014.
The original data looks like this
CREATE TABLE #s (grp varchar(3), id varchar(4), acc varchar(5), pr float, pos_live float, pos_yest float, fnd varchar(2))
INSERT INTO #s Values ('GR1','VX1','CFD01',25,100,95,'KY')
INSERT INTO #s Values ('GR1','VX1','UCD01',24.5,30,20,'UC')
INSERT INTO #s Values ('GR1','VX1','US1',25,10,95,'US')
INSERT INTO #s Values ('GR1','VX2','CFD01',20,10,10,'KY')
INSERT INTO #s Values ('GR1','VX2','UCD01',19,5,5,'UC')
INSERT INTO #s Values ('GR1','FVS1','CFD01',24,1,1,'KY')
INSERT INTO #s Values ('GR1','FVS1','UCD01',23,1,1,'UC')
INSERT INTO #s Values ('GR1','FVS1','EU1',23.5,1,1,'EU')
INSERT INTO #s Values ('GR2','FVS1','CFD02',24,10,10,'KY')
INSERT INTO #s Values ('GR2','FVS1','UCD02',23,10,10,'UC')
INSERT INTO #s Values ('GR2','FVS1','EU2',23.5,10,10,'EU')
And I would like to get this
I am struggling to use the pivot function on multiple columns and additionaly display dynamic column names in the result.
You can try to use condition aggregate function to make it, SUM with CASE WHEN
SELECT grp,
id,
SUM(CASE WHEN fnd = 'KY'THEN pr ELSE 0 END) pr_ky,
SUM(CASE WHEN fnd = 'UC'THEN pr ELSE 0 END) pr_uc,
SUM(CASE WHEN fnd = 'US'THEN pr ELSE 0 END) pr_us,
SUM(CASE WHEN fnd = 'EU'THEN pr ELSE 0 END) pr_eu,
SUM(CASE WHEN fnd = 'KY'THEN pos_live ELSE 0 END),
SUM(CASE WHEN fnd = 'UC'THEN pos_live ELSE 0 END),
SUM(CASE WHEN fnd = 'US'THEN pos_live ELSE 0 END),
SUM(CASE WHEN fnd = 'EU'THEN pos_live ELSE 0 END),
SUM(CASE WHEN fnd = 'KY'THEN pos_yest ELSE 0 END),
SUM(CASE WHEN fnd = 'UC'THEN pos_yest ELSE 0 END),
SUM(CASE WHEN fnd = 'US'THEN pos_yest ELSE 0 END),
SUM(CASE WHEN fnd = 'EU'THEN pos_yest ELSE 0 END)
FROM #s
GROUP BY grp,id
ORDER BY grp
sqlfiddle
You don't really want to use PIVOT here explicitly because it is meant to pivot one column, not multiple. Conditional aggregation like in #D-Shih's answer is the way you want to go, except you can't do that if you expect the query to change with the data. So you can use dynamic SQL:
DECLARE #s0 nvarchar(max) = N'',
#s1 nvarchar(max) = N'',
#s2 nvarchar(max) = N'',
#s3 nvarchar(max) = N'',
#sql nvarchar(max) = N'';
;WITH cols AS
(
SELECT fnd, efnd = char(39) + fnd + char(39) FROM #s
)
SELECT #s0 += N',
acc_' + fnd + N' '
+ N' = MAX(CASE fnd WHEN ' + efnd
+ N' THEN acc END)',
#s1 += N',
pr_' + fnd + N' '
+ N' = SUM(CASE fnd WHEN ' + efnd
+ N' THEN pr ELSE 0 END)',
#s2 += N',
pos_live_' + fnd
+ N' = SUM(CASE fnd WHEN ' + efnd
+ N' THEN pos_live ELSE 0 END)',
#s3 += N',
pos_yest_' + fnd
+ N' = SUM(CASE fnd WHEN ' + efnd
+ N' THEN pos_yest ELSE 0 END)'
FROM cols GROUP BY fnd, efnd;
SET #sql += N'SELECT grp, id' + #s0 + #s1 + #s2 + #s3 + N'
FROM #s GROUP BY grp, id ORDER BY grp;';
PRINT #sql;
EXEC sys.sp_executesql #sql;
Print output:
SELECT grp, id,
acc_EU = MAX(CASE fnd WHEN 'EU' THEN acc END),
acc_KY = MAX(CASE fnd WHEN 'KY' THEN acc END),
acc_UC = MAX(CASE fnd WHEN 'UC' THEN acc END),
acc_US = MAX(CASE fnd WHEN 'US' THEN acc END),
pr_EU = SUM(CASE fnd WHEN 'EU' THEN pr ELSE 0 END),
pr_KY = SUM(CASE fnd WHEN 'KY' THEN pr ELSE 0 END),
pr_UC = SUM(CASE fnd WHEN 'UC' THEN pr ELSE 0 END),
pr_US = SUM(CASE fnd WHEN 'US' THEN pr ELSE 0 END),
pos_live_EU = SUM(CASE fnd WHEN 'EU' THEN pos_live ELSE 0 END),
pos_live_KY = SUM(CASE fnd WHEN 'KY' THEN pos_live ELSE 0 END),
pos_live_UC = SUM(CASE fnd WHEN 'UC' THEN pos_live ELSE 0 END),
pos_live_US = SUM(CASE fnd WHEN 'US' THEN pos_live ELSE 0 END),
pos_yest_EU = SUM(CASE fnd WHEN 'EU' THEN pos_yest ELSE 0 END),
pos_yest_KY = SUM(CASE fnd WHEN 'KY' THEN pos_yest ELSE 0 END),
pos_yest_UC = SUM(CASE fnd WHEN 'UC' THEN pos_yest ELSE 0 END),
pos_yest_US = SUM(CASE fnd WHEN 'US' THEN pos_yest ELSE 0 END)
FROM #s GROUP BY grp, id ORDER BY grp;
Execution results:
grp
id
acc_EU
acc_KY
acc_UC
acc_US
pr_EU
pr_KY
pr_UC
pr_US
pos_live_EU
pos_live_KY
pos_live_UC
pos_live_US
pos_yest_EU
pos_yest_KY
pos_yest_UC
pos_yest_US
GR1
FVS1
EU1
CFD01
UCD01
null
23.5
24
23
0
1
1
1
0
1
1
1
0
GR1
VX1
null
CFD01
UCD01
US1
0
25
24.5
25
0
100
30
10
0
95
20
95
GR1
VX2
null
CFD01
UCD01
null
0
20
19
0
0
10
5
0
0
10
5
0
GR2
FVS1
EU2
CFD02
UCD02
null
23.5
24
23
0
10
10
10
0
10
10
10
0
Example db<>fiddle
I have temp table data in sql. I need modify data in that table.
Please find snapshot attached
I need to have a col having month data like for 01-03 jan-mar
this is code I have written. It's not working:
DECLARE #month VARCHAR(50) -- month
DECLARE #year VARCHAR(256) -- year
DECLARE #monthf VARCHAR(256) -- year
DECLARE #months VARCHAR(256) -- year
DECLARE db_cursor CURSOR FOR
SELECT months,[year] FROM #temp where len(months)>4
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #month,#year
WHILE ##FETCH_STATUS = 0
BEGIN
IF SUBSTRING(#month,0,3) = '01'
set #monthf='Jan'
ELSE IF SUBSTRING(#month,0,3) = '02'
set #monthf='Feb'
ELSE IF SUBSTRING(#month,0,3) = '03'
set #monthf='Mar'
ELSE IF SUBSTRING(#month,0,3) = '04'
set #monthf='Apr'
ELSE IF SUBSTRING(#month,0,3) = '05'
set #monthf='May'
ELSE IF SUBSTRING(#month,0,3) = '06'
set #monthf='Jun'
ELSE IF SUBSTRING(#month,0,3) = '07'
set #monthf='Jul'
ELSE IF SUBSTRING(#month,0,3) = '08'
set #monthf='Aug'
ELSE IF SUBSTRING(#month,0,3) = '09'
set #monthf='Sep'
ELSE IF SUBSTRING(#month,0,3) = '10'
set #monthf='Oct'
ELSE IF SUBSTRING(#month,0,3) = '11'
set #monthf='Nov'
ELSE IF SUBSTRING(#month,0,3) = '12'
set #monthf='Dec'
IF SUBSTRING(#month,4,2) = '01'
set #months='Jan'
ELSE IF SUBSTRING(#month,4,2) = '02'
set #months='Feb'
ELSE IF SUBSTRING(#month,4,2) = '03'
set #months='Mar'
ELSE IF SUBSTRING(#month,4,2) = '04'
set #months='Apr'
ELSE IF SUBSTRING(#month,4,2) = '05'
set #months='May'
ELSE IF SUBSTRING(#month,4,2) = '06'
set #months='Jun'
ELSE IF SUBSTRING(#month,4,2) = '07'
set #months='Jul'
ELSE IF SUBSTRING(#month,4,2) = '08'
set #months='Aug'
ELSE IF SUBSTRING(#month,4,2) = '09'
set #months='Sep'
ELSE IF SUBSTRING(#month,4,2) = '10'
set #months='Oct'
ELSE IF SUBSTRING(#month,4,2) = '11'
set #months='Nov'
ELSE IF SUBSTRING(#month,4,2) = '12'
set #months='Dec'
update #temp set [Month]= where months=
Delete from #temp where months=SUBSTRING(#month,0,3) and [Year]=#year
Delete from #temp where months=SUBSTRING(#month,4,2) and [Year]=#year
FETCH NEXT FROM db_cursor INTO #month,#year
END
CLOSE db_cursor
DEALLOCATE db_cursor
I need another column with month names like: for 01-03 it should give jan-mar
Can you please help me out? I need a separate column for month string data.
You don't need a cursor at all.
IF OBJECT_ID('tempdb..#Data') IS NOT NULL
DROP TABLE #Data
CREATE TABLE #Data (
Month VARCHAR(100),
ResultMonthText VARCHAR(100))
INSERT INTO #Data (
Month)
VALUES
('01-03'),
('07'),
('03'),
('03-05'),
('05-09'),
('02')
;WITH ParsedMonths AS
(
SELECT
D.Month,
D.ResultMonthText,
First = CONVERT(INT, SUBSTRING(D.Month, 1, 2)),
Second = CONVERT(INT, NULLIF(SUBSTRING(D.Month, 4, 2), ''))
FROM
#Data AS D
),
MonthNames AS
(
SELECT
D.Month,
D.ResultMonthText,
FirstAsName = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, D.First, 0) - 1 ),
1,
3),
SecondAsName = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, D.Second, 0) - 1 ),
1,
3)
FROM
ParsedMonths AS D
)
UPDATE D SET
ResultMonthText = D.FirstAsName + ISNULL('-' + D.SecondAsName, '')
FROM
MonthNames AS D
SELECT
*
FROM
#Data AS D
/*
Result:
Month ResultMonthText
------- ------------
01-03 Jan-Mar
07 Jul
03 Mar
03-05 Mar-May
05-09 May-Sep
02 Feb
*/
EDIT: Do this if you still want to keep your cursor (although I strongly suggest you stop using them whenever you can):
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #month,#year
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #FirstMonthNumber INT = CONVERT(INT, SUBSTRING(#month, 1, 2))
DECLARE #SecondMonthNumber INT = CONVERT(INT, NULLIF(SUBSTRING(#month, 4, 2), ''))
DECLARE #FirstMonthText VARCHAR(10) = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, #FirstMonthNumber, 0) - 1 ),
1,
3)
DECLARE #SecondMonthText VARCHAR(10) = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, #SecondMonthNumber, 0) - 1 ),
1,
3)
update #temp set
YourNewMonthColumn = #FirstMonthText + ISNULL('-' + #SecondMonthText, '')
WHERE
months = #month
FETCH NEXT FROM db_cursor INTO #month,#year
END
I don't know why you update the column and then delete the row also.
Maybe
update #temp set [Month] = #monthf where months = #months
We have a very old vb.net winforms application which uses sql server as its database. Our application is such that we have to store changes in various modules in our system eg. CustomerAccident, CustomerAdmission etc and also insert a brief description and lots of other guids to establish relation between different type of events happening into our dailyReporting table(i.e data is stored in a very normalized way). When we display data from this reporting table we have created a view to help us to give a de-normalized form of the data which we then display in the customer record.
As you can imagine for few of our customers this reporting table has now more than a million rows. now every time clients try to view the Customer record because the query has to go through so many rows it is taking a lot of time for the query to run and in some cases blocking few tables which is causing problems for other users.
To solve this we were thinking of creating a whole new reporting db and storing the information there in a de-normalized form and filling various tables there in the same as we would in the view just by using triggers.
I know this might be bit vague question to ask but i am looking for other ideas if anyone else had experience with this situation.
The following is the sql query being used to get the information
exec sp_executesql N'
SELECT
''Customer Report'' AS type
, CASE --Record Type
WHEN cv_customerDailyReport.type & 12 = 12
OR cv_customerDailyReport.type & 19 = 19
OR cv_customerDailyReport.type & 65 = 65 THEN
''ABC''
WHEN cv_customerDailyReport.type & 54 = 54 THEN
''CDE''
WHEN cv_customerDailyReport.type & 96 = 96 THEN
''REW''
ELSE
cv_customerDailyReport.Description
END AS ReportType
, CASE -- SUB TYPE
WHEN cv_customerDailyReport.type & 258 = 258 THEN
''QWE''
WHEN cv_customerDailyReport.type & 321 = 321 THEN
''RTY''
WHEN cv_customerDailyReport.type & 1 = 1 THEN
''AGX''
WHEN cv_customerDailyReport.type & 8 = 8 THEN
''CTE''
WHEN cv_customerDailyReport.type & 16 = 16 THEN
''TYU''
ELSE
''other''
END AS subtype
, cv_customerDailyReport.customerDailyRecord AS ''guid''
, cv_customerDailyReport.ActionDate
, COALESCE(userTable.name,''exStaff'') as ''By''
, CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=1 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE ''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Not change''
END
)
WHEN cv_customerDailyReport.Improvement=3 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Bad''
END
)
END AS ''Improvement''
, CASE
WHEN cv_customerDailyReport.type & 258 = 258 THEN
convert(varchar,cv_customerDailyReport.measurementValue) + '' '' + chemist.Name -- + '', '' + cv_customerDailyReport.observationText
+ '' '' +
(
CASE
WHEN (cv_customerDailyReport.comment<>'''' or cv_customerDailyReport.comment<>null) THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'') THEN
(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'')
ELSE
''Please comment''
END
)
+ '' - ''+
(
CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=1 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE
''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Unchanged''
END
)
WHEN cv_customerDailyReport.Improvement=3 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Deteriorated''
END
)
END
)
+ '' - '' + cv_customerDailyReport.comment
ELSE
''''
END
)
WHEN cv_customerDailyReport.type & 321 = 321
AND cv_customerDailyReport.measurementValue <> 0 THEN
-- measurment
CASE
WHEN (MeasurementType.StatusFlags & 16 = 16 ) THEN
cv_customerDailyReport.measurementValueAndType
+ '' - '' + convert(varchar,COALESCE(CONVERT(INT,cv_customerDailyReport.measurementValue),0))
+ ''/'' + convert(varchar,COALESCE(CONVERT(INT,cv_customerDailyReport.measurementValue2),0))
ELSE
cv_customerDailyReport.measurementValueAndType
+ '' - '' + convert(varchar,COALESCE(cv_customerDailyReport.measurementValue,0))
END
+ '' '' +
(
CASE
WHEN(cv_customerDailyReport.comment <> ''''
or cv_customerDailyReport.comment<>null) THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'') THEN
(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'')
ELSE
''Do you think the person’s quality of life has improved?''
END
)
+ '' - '' +
(
CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=1 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE
''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Unchanged''
END
)
WHEN cv_customerDailyReport.Improvement=3 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Deteriorated''
END
)
END
)
+ '' - '' + cv_customerDailyReport.comment
ELSE
''''
END
)
WHEN cv_customerDailyReport.type & 485 = 485 THEN
(
SELECT top 1
CASE
WHEN pain = 1 THEN
''DER = True'' + '' - ''
ELSE
''''
END
+
CASE
WHEN woundGrade = 1 THEN
''Grade : '' + ''Ungraded'' + '' - ''
WHEN woundGrade = 258 THEN
''Grade : '' +''Grade 1'' + '' - ''
WHEN woundGrade = 3 THEN
''Grade : '' +''Grade 258'' + '' - ''
WHEN woundGrade = 321 THEN
''Grade : '' +''Grade 3'' + '' - ''
WHEN woundGrade = 5 THEN
''Grade : '' +''Grade 321'' + '' - ''
ELSE
''''
END
+
CASE
WHEN NullIF(Location , '''') IS NOT NULL THEN
''Location : '' + Location + '' - ''
ELSE
''''
END
+
'' Width : '' + ISNULL(convert(VARCHAR ,woundWidth),''N/A'') + '' - '' +
'' Lenth : '' + ISNULL(convert(VARCHAR ,woundLength), ''N/A'')
FROM
customerWoundHistory
WHERE
customerWoundHistoryId = cv_customerDailyReport.customerDailyRecord
)
ELSE
cv_customerDailyReport.observationText
+ '' '' +
(
CASE
WHEN (cv_customerDailyReport.comment <> ''''
or cv_customerDailyReport.comment<>null) THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'') THEN
(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'')
ELSE
''Do you think quality has improved?''
END
)
+ '' - ''+
(
CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=5 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE
''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Unchanged''
END
)
WHEN cv_customerDailyReport.Improvement=31 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Deteriorated''
END
)
END
)
+ '' - '' + cv_customerDailyReport.comment
ELSE
''''
END
)
END AS ''action''
, cv_customerDailyReport.comments AS ''text''
, cv_customerDailyReport.timestamp
, cv_customerDailyReport.Status
, CASE
WHEN(attachmentTable.category=''QWE'') THEN
1
ELSE
0
END AS ''hasattachment''
, CASE
WHEN(cv_customerDailyReport.type & #sign = #sign) THEN
1
ELSE
0
END AS ''hasBeenLookedAt''
, CASE
WHEN(cv_customerDailyReport.type & 65536 = 65536) THEN
1
ELSE
0
END AS ''IsAvailable''
, cv_customerDailyReport.sourceSystem
, cv_customerDailyReport.ADLIDs
, CASE
WHEN DATEDIFF(MINUTE, actionDate, completedDate) < 0 THEN
0
ELSE
DATEDIFF(MINUTE, actionDate, completedDate)
END AS Duration
FROM
cv_customerDailyReport
LEFT OUTER JOIN userTable on cv_customerDailyReport.createdbyuser = userTable.guid
LEFT OUTER JOIN chemist on cv_customerDailyReport.medicine = chemist.medication
LEFT OUTER JOIN enumnerationTable as MeasurementType ON cv_customerDailyReport.measurementType = MeasurementType.guid
LEFT JOIN attachmentTable on attachmentTable.parentID=cv_customerDailyReport.customerDailyRecord and attachmentTable.category=''DailyAttachmentFile''
WHERE
ActionDate <= getDate()
AND cv_customerDailyReport.status IN (#completed, #completedAndPaid, #Void, #Cancelled, #authorised)
AND cv_customerDailyReport.customer = #customer
AND (
cv_customerDailyReport.ActionDate >= #FromDate
OR cv_customerDailyReport.timestamp > #FromTimeStamp
)
AND (
cv_customerDailyReport.categoryDescription LIKE #filterText
OR cv_customerDailyReport.observationText LIKE #filterText
OR cv_customerDailyReport.comments LIKE #filterText
OR chemist.Name LIKE #filterText
)
AND (
(
#maxAge = 0 AND cv_customerDailyReport.ActionDate >= #FromDate
)
OR (
cv_customerDailyReport.ActionDate >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''event'' AS type
, CASE customerHistory.type
WHEN 0 THEN
''UIO''
WHEN 258 THEN
''DER''
WHEN 3 THEN
''WER''
WHEN 1 THEN
''SDE''
ELSE
''Diary''
END AS subtype
, ''event'' AS categoryType
, customerHistory.guid AS ''guid''
, customerHistory.dateStarted AS ActionDate
, ISNULL ((SELECT name FROM userTable WHERE individualCustomerHostory.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' AS ''Improvement''
, customerHistory.comments AS ''action''
, individualCustomerHostory.completedNotes AS ''text''
, individualCustomerHostory.timestamp
, individualCustomerHostory.status
, CASE
WHEN(attachmentTable.category = ''DailyAttachmentFile'') THEN
1
ELSE
0
END AS ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerHistory
LEFT OUTER JOIN roomInfo on customerHistory.room = roomInfo.unit
LEFT JOIN attachmentTable on attachmentTable.parentID=customerHistory.guid AND attachmentTable.category = ''DailyAttachmentFile''
WHERE
customerHistory.customer = #customer
AND (
customerHistory.lastUpdated >= #FromDate
OR individualCustomerHostory.timestamp > #FromTimeStamp
)
AND (
(
roomInfo.shortName LIKE #filterText
OR roomInfo.fullName LIKE #filterText
)
OR customerHistory.type > 0
)
AND (
(
#maxAge = 0 AND customerHistory.dateStarted >= #FromDate
)
OR (
customerHistory.dateStarted >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''Calendar appointment'' AS ''type''
, ''Calendar appointment'' AS ''categoryType''
, ''Calendar appointment'' AS ''subtype''
, customerAppointmentsAttendees.appointment AS ''guid''
, customerAppointments.StartTime AS ''ActionDate''
, ISNULL((SELECT name FROM userTable WHERE customerAppointments.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' AS ''Improvement''
, customerAppointments.Description AS ''action''
, customerAppointments.completedNotes AS ''text''
, customerAppointments.timestamp
, 0
, 0 as ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerAppointments
JOIN customerAppointmentsAttendees on customerAppointmentsAttendees.appointment = customerAppointments.appointment
WHERE
customerAppointments.completed = 1
AND customerAppointmentsAttendees.Attendee = #customer
AND (
(
#maxAge = 0 AND customerAppointments.StartTime >= #FromDate
)
OR (
customerAppointments.StartTime >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''Accident'' AS type
, ''Accident'' AS subtype
, ''Accident'' AS categoryType
, customerAccident.accident AS ''guid''
, customerAccident.accidentDate AS ActionDate
, ISNULL((SELECT name FROM userTable WHERE customerAccident.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' as ''Improvement''
, customerAccident.accidentRef
+ '' - '' +
CASE
WHEN customerAccident.personalInjury = 1 THEN
''Injury''
WHEN customerAccident.nearMiss = 1 THEN
''Near miss''
WHEN customerAccident.propertyDamage = 1 THEN
''Property damage''
WHEN customerAccident.risk = 1 THEN
''Risk''
ELSE
''Other''
END AS ''action''
, CAST(customerAccident.injuryNature AS VARCHAR(4096)) AS ''text''
, customerAccident.timestamp
, 0
, 0 as ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerAccident
WHERE
customerAccident.customer = #customer
AND (
(
#maxAge = 0 AND customerAccident.accidentDate >= #FromDate
)
OR (
customerAccident.accidentDate >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''Incident'' AS type
, ''Incident'' AS subtype
, ''Incident'' AS categoryType
, customerIncident.incident AS ''guid''
, customerIncident.incidentDate AS ActionDate
, ISNULL((SELECT name FROM userTable WHERE customerIncident.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' AS ''Improvement''
, customerIncident.incidentRef + '' - '' + customerIncident.intensity AS ''action''
, CAST(customerIncident.narrative AS VARCHAR(4096)) AS ''text''
, customerIncident.timestamp
, 0
, 0 AS ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerIncident
WHERE
customerIncident.person = #customer
AND (
(
#maxAge = 0 AND customerIncident.incidentDate >= #FromDate
)
OR (
customerIncident.incidentDate >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
ORDER BY
ActionDate Desc
',N'#customer uniqueidentifier,#FromDate datetime,#FromTimeStamp varbinary(8),#filterText nvarchar(258),#completed int,#completedAndPaid int,#Void int,#Cancelled int,#report nvarchar(9),#CurrentDate datetime,#sign int,#authorised int,#maxAge int',#customer='C661135D-0331-4544-82A7-335C2E7D40AF',#FromDate='2014-10-30 00:00:00',#FromTimeStamp=0x0000000000000000,#filterText=N'%%',#completed=15,#completedAndPaid=18,#Void=17,#Cancelled=20,#report=N'Customer Support',#CurrentDate='2014-11-06 00:00:00',#sign=524,#authorised=21,#maxAge=0
The view is cv_customerDailyReport and the tables customerHistory have been indexed. We have run the execution plans and tried to put more indexes based on them but still we are experiencing slowness.
Any help would be much appreciated.
I have a stored procedure that looks something like this :
CREATE PROCEDURE [dbo].[spRS_Get]
#Year Varchar(20),
#Month Varchar(20)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Paramdate datetime;
DECLARE #ParamYear varchar(4);
DECLARE #ParamMonth varchar(2);
DECLARE #Concatt varchar(10);
SET #ParamYear = #Year;
SET #ParamMonth = #Month;
SET #Concatt = #ParamMonth + '-' + '01' + '-' + #ParamYear;
SET #Paramdate = CONVERT(datetime, #Concatt);
SELECT Item
,SUM(CASE WHEN [MONTH] = month(#ParamDate) THEN Sales END) AS month(#ParamDate)
,SUM(CASE WHEN [MONTH] = month(#ParamDate) - 1 THEN Sales END) AS month(#ParamDate) - 1,
,SUM(CASE WHEN [MONTH] = month(#ParamDate) THEN Sales END) - SUM(CASE WHEN [MONTH] = month(#ParamDate) - 1 THEN Sales END) AS month(#ParamDate) - month(#ParamDate) - 1
FROM ABC
GROUP BY Item
In the above query , the part after the AS causes the error.
I want to use the parameter name as the name of the column , but it gives me an error. Is there a way I can use
the parameter name as the name of the month ?
You can only do that by building the select statement as a string and then executing it using the sp_executesql command.
So you'd get something like this:
declare #month0 varchar(2) = cast(month(#paramdate) as varchar(2));
declare #month1 varchar(2) = cast((month(#ParamDate) - 1) as varchar(2));
declare #month2 varchar(2) =
cast((month(#ParamDate) - month(#ParamDate) - 1) as varchar(2));
declare s nvarchar(1024) =
'SELECT Item
, SUM(CASE WHEN [MONTH] = month(#d) THEN Sales END)
AS ''' + #month0 +
''' , SUM(CASE WHEN [MONTH] = month(#d) - 1 THEN Sales END)
AS ''' + #month1 +
''' , SUM(CASE WHEN [MONTH] = month(#d) THEN Sales END) -
SUM(CASE WHEN [MONTH] = month(#d) - 1 THEN Sales END)
AS ''' + #month2 +
''' FROM ABC GROUP BY Item';
EXEC sp_executesql #s, N'#d DATETIME', #ParamDate;
DECLARE #temp TABLE
(
iLeadID INT ,
Title VARCHAR(MAX) ,
AlertDate DATETIME
)
DECLARE #iLeadID INT
DECLARE #getiLeadID CURSOR
SET
#getiLeadID = CURSOR FOR
SELECT iLeadID FROM LeadsContracts
OPEN #getiLeadID
FETCH NEXT FROM #getiLeadID INTO #iLeadID
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #temp
SELECT #iLeadID ,
'Disclosure' ,
CONVERT(VARCHAR, dtDisclosure, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtDisclosure IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
'Due Diligence' ,
CONVERT(VARCHAR, dtDueDiligence, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtDueDiligence IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
'Finance Appraisals' ,
CONVERT(VARCHAR, dtFinanceAppraisals, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtFinanceAppraisals IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
sFreeTextCustom1 ,
CONVERT(VARCHAR, dtFreeTextDate1, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtFreeTextDate1 IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
sFreeTextCustom2 ,
CONVERT(VARCHAR, dtFreeTextDate2, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtFreeTextDate2 IS NOT NULL
FETCH NEXT FROM #getiLeadID INTO #iLeadID
END
CLOSE #getiLeadID
DEALLOCATE #getiLeadID
SELECT * ,
( CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sEmail
FROM UserAccount objUA
WHERE EXISTS ( SELECT iUserID
FROM GroupAgent
WHERE iUserID = objUA.iUserID
AND iGroupID = t1.GroupID
AND btAdminFlg = ( (1) ) )
)
ELSE ''
END ) AS AdminEmail
FROM ( SELECT * ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sFirstName + ' ' + sLastName
FROM Lead
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS LeadName ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sEmail
FROM Lead
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS LeadEmail ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
iUserID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS AgentID ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sFirstName + ' ' + sLastName
FROM UserAccount
WHERE iUserID = ( SELECT
iUserID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
)
ELSE ''
END AS AgentName ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sEmail
FROM UserAccount
WHERE iUserID = ( SELECT
iUserID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
)
ELSE ''
END AS AgentEmail ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
iGroupID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS GroupID ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sName
FROM [Group]
WHERE iGroupID = ( SELECT
iGroupID
FROM AssignLeadUser
WHERE
iLeadID = objTemp.iLeadID
)
)
ELSE ''
END AS GroupName
FROM #temp objTemp
) AS t1
ORDER BY AlertDate ASC
it gives me an output of 2013-04-04 00:00:00.000 in the AlertDate column
I want to get only the date (no time) like this: 2013-04-04" in the AlterDate column.
Could anybody please help me to advice some query or update my code?
Thanks in advance
You can use the date type instead of datetime
declare #temp Table
(
iLeadID int,
Title varchar(Max),
AlertDate date
)
You have AlterDate typed as a DATETIME. If you only want to store the date, use a DATE data type. An added benefit of doing this is that the DATE data type only takes 3 bytes instead of the DATETIME's 8 bytes.
If you subsequently need to turn AlterDate back into a DATETIME, it will use the midnight value that you're currently seeing.