Error while using the Group By Clause - sql

I am getting the sql server error "the text ntext and image data types cannot be compared or sorted except when using is null or like" while executing
SELECT r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A],
CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r
INNER JOIN table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId
INNER JOIN table_user AS u ON r.user_id = u.user_id
INNER JOIN table_labs AS l ON r.lab_id = l.lab_id
INNER JOIN table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY r.Shift, l.lab_title, u.user_name
Don't know what's the problem. I have used aggregate function also with it, just for formality but it's not working.

I'm guessing your r.Shift column is a text or ntext type. Because of this it cannot be used in a group by
One option might be to use a CAST on the suspect column, but you might loose data. Example:
SELECT r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r INNER JOIN
table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
table_user AS u ON r.user_id = u.user_id INNER JOIN
table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY CAST(r.Shift as varchar(max), l.lab_title, u.user_name
You could also look at querying the data without the text column and then doing a second query to get the missing column. Example:
with temp as
(
SELECT l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r INNER JOIN
table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
table_user AS u ON r.user_id = u.user_id INNER JOIN
table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY l.lab_title, u.user_name
)
SELECT r.Shift, t.lab_title AS [Assigned Lab], t.user_name AS [L/A] --etc
FROM table_roaster_time_table AS r
INNER JOIN temp as t
on r.id = t.id --or whatver
Also, this SQL seems unnecessary:
r.timeId = t.timeId AND r.timeId = t.timeId

Related

Can I get nested column in stored procedure?

I have a Select into Stored Procedure:
SELECT
' ' AS MonthName
,gd.Month
,ISNULL(SUM(gd.Meta),0) AS Total
INTO #Meta
FROM [dbo].[Goal] g (NOLOCK)
INNER JOIN [dbo].[GoalDetail] gd (NOLOCK)
ON g.Id = gd.IdGoal
INNER JOIN [dbo].[GoalClassification] gc (NOLOCK)
ON gd.IdClassification = gc.Id
WHERE gc.Id IN (2,7)
AND g.Year = YEAR(GETDATE())
AND gd.Month = MONTH(GETDATE())
GROUP BY gd.Month
I want to get Foreign Key BranchOfficeId, but it is nested like:
Table Goal have FKDepartment and Department have fk of BranchOfficeId, how can I call this BranchOfficeId into my stored? Regards
----Update-----
SELECT
' ' AS MonthName
,gd.Month
,ISNULL(SUM(gd.Meta),0) AS Total
INTO #Meta
FROM [dbo].[Goal] g (NOLOCK)
INNER JOIN [dbo].[GoalDetail] gd (NOLOCK)
ON g.Id = gd.IdGoal
INNER JOIN [dbo].[GoalClassification] gc (NOLOCK)
ON gd.IdClassification = gc.Id
INNER JOIN [dbo].[Department] dep (NOLOCK) // there I call department but now how can I call branchOfficeId?
ON g.IdDepartment = dep.Id
WHERE gc.Id IN (2,7)
AND g.Year = YEAR(GETDATE())
AND gd.Month = MONTH(GETDATE())
GROUP BY gd.Month

Too many results in query

I'm fetching some data from our database in MSSQL. Out of this data I want to determine who created the client entry and who took the first payment from this client.
There can be many payment entries for a client on a single booking/enquiry and at the moment, my query shows results for each payment. How can I limit the output to only show the first payment entry?
My query:
SELECT
c.FirstName,
c.LastName,
c.PostalCode,
o.OriginOfEnquiry,
s.SuperOriginName,
c.DateOfCreation,
DATEDIFF(day, c.DateOfCreation, p.DateOfCreation) AS DaysToPayment,
pc.PackageName,
CONCAT(u.FirstName, ' ', u.LastName) AS CreateUser,
(SELECT CONCAT(u.FirstName, ' ', u.LastName)
WHERE u.UserID = p.UserID ) AS PaymentUser
FROM tblBookings b
INNER JOIN tblPayments p
ON b.BookingID = p.BookingID
INNER JOIN tblEnquiries e
ON e.EnquiryID = b.EnquiryID
INNER JOIN tblCustomers c
ON c.CustomerID = e.CustomerID
INNER JOIN tblOrigins o
ON o.OriginID = e.OriginID
INNER JOIN tblSuperOrigins s
ON s.SuperOriginID = o.SuperOriginID
INNER JOIN tblBookingPackages bp
ON bp.bookingID = p.BookingID
INNER JOIN tblPackages pc
ON pc.PackageID = bp.packageID
INNER JOIN tblUsers u
ON u.UserID = c.UserID
WHERE c.DateOfCreation >= '2016-06-01' AND c.DateOfCreation < '2016-06-30'
AND p.PaymentStatusID IN (1,2)
AND e.CustomerID = c.CustomerID
AND p.DeleteMark != 1
AND c.DeleteMark != 1
AND b.DeleteMark != 1
;
I tried adding a "TOP 1" to the nested select statement for PaymentUser, but it made no difference.
you can use cross apply with top 1:
FROM tblBookings b
cross apply
(select top 1 * from tblPayments p where b.BookingID = p.BookingID) as p
Instead of table tblPayments specify sub-query like this:
(SELECT TOP 1 BookingID, UserID, DateOfCreation
FROM tblPayments
WHERE DeleteMark != 1
AND PaymentStatusID IN (1,2)
ORDER BY DateOfCreation) as p
I'm assuming that tblPayments has a primary key column ID. If it is true, you can use this statment:
FROM tblBookings b
INNER JOIN tblPayments p ON p.ID = (
SELECT TOP 1 ID
FROM tblPayments
WHERE BookingID = b.BookingID
AND DeleteMark != 1
AND PaymentStatusID IN (1,2)
ORDER BY DateOfCreation)

Query takes forever to output info - tips on optimization

I have a query that works awesomely - but - it takes about 10 minutes to load up. Which is insane. And I would like for it to run faster than it currently does now.
I was wondering if there were any tips I could take to optimize my query to make it run faster?
select DISTINCT
c.PaperID,
cdd.CodesF,
c.PageCount,
prr.projectname,
u.firstname + ' ' + u.lastname as Name,
ett.EventName,
cast(c.AssignedDate as DATE) [AssignedDate],
cast(ev.EventCompletionDate as DATE) [CompletionDate],
ar.ResultDescription,
a.Editor
from tbl_Papers c
left outer join (select cd.PaperId, count(*) as CodesF
from tbl_PaperCodes cd group by cd.PaperId) cdd
on cdd.PaperId = c.PaperId
left outer join
(SELECT
wfce.PaperEventActionNum,
c.PaperId,
CONVERT(varchar,wfce.ActionDate,101) CompletionDate,
pr.ProjectName,
wfce.ActionUserId,
u.firstname+' '+u.lastname [Editor]
FROM
dbo.tbl_WFPaperEventActions wfce
INNER JOIN dbo.tbl_Papers c ON wfce.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
INNER JOIN tbl_Projects pr ON s.ProjectId=pr.ProjectId
INNER JOIN tbl_Users u ON wfce.ActionUserId=u.UserId
WHERE
wfce.EventId = 204
AND c.Papersource =0
GROUP BY
wfce.PaperEventActionNum,
c.PaperId,
CONVERT(varchar,wfce.ActionDate,101),
pr.ProjectName,
wfce.ActionUserId,
u.firstname+' '+u.lastname
)a ON a.PaperId=c.PaperId,
tbl_Providers p, tbl_Sites s,
tbl_Projects prr, tbl_WFPaperEvents ev,
tbl_Users u, tbl_WFPaperEventTypes ett,
tbl_WFPaperEventActions arr, tbl_WFPaperEventActionResults ar
where s.SiteId = p.SiteId
and p.ProviderId = c.ProviderId
and s.ProjectId = prr.ProjectId
and ev.PaperId = c.PaperId
and ev.EventCreateUserId = u.UserId
and ev.EventCompletionDate >= dateadd(day,datediff(day,1,GETDATE()),0)
and ev.EventCompletionDate < dateadd(day,datediff(day,0,GETDATE()),0)
and ev.EventStatusId = 3
and ev.EventId in (201, 203)
and c.Papersource =0--Offshore
and ev.EventId=ett.EventID
and arr.PaperId=c.PaperId
and arr.EventId=ev.EventId
and arr.EventId=ar.EventID
and arr.ActionResultId=ar.ResultID
and arr.ActionResultId in (1,2,3,4)
order by paperid, u.FirstName + ' ' + u.LastName
You need to re-look carefully at every piece of this query and ask yourself, is that needed?
Take the subquery with alias a.
It joins 6 tables, but if you trace up to your final select clause only [Editor] is supplied from that alias. So do you need 6 tables to arrive at editor? No you don't in fact you only need 2 tbl_WFPaperEventActions and tbl_Users. Furthermore, this subquery is grouping by 6 items including a date, but 3 of those items are not used anywhere else in the overall query - so why go include these in the grouping? This allows us to drop 3 of the joined tables.
Of the remaining 3 grouping items a further 1 can be substituted to avoid the join between tbl_WFPaperEventActions and tbl_Papers because the join condition is "wfce.PaperId = c.PaperId", all we need then is to group by wfce.PaperId instead of c.PaperId
Finally we are then interested in the field wfce.PaperEventActionNum this is supplied by the subquery but isn't used in the larger query? Why provide that field is it isn't used? Well it turns out that it should be used to complete a join. The subquery aliased as a needs joining into the outer query on both PaperEventActionNum and PaperId. This by the way also requires that the whole subquery needs to be pushed down the joining structure to comply with ANSI join syntax rules.
Never "mix" ANSI join syntax with joins done "the old fashioned way"
This really is a recipe for a disaster.
Below I have "started" some amendments to your query, but I cannot really complete it as I have no way to test any part of it; and I don't know your data model at all.
Personally, I would re-start this query from scratch, starting lean and adding item by item to ensure it remains lean.
SELECT DISTINCT /* distinct isn't a good solution here */
c.PaperID
, cdd.CodesF
, c.PageCount
, prr.projectname
, u.firstname + ' ' + u.lastname AS Name
, ett.EventName
, CAST(c.AssignedDate AS date) [AssignedDate]
, CAST(ev.EventCompletionDate AS date) [CompletionDate]
, ar.ResultDescription
, a.Editor
FROM tbl_Papers c
LEFT OUTER JOIN ( -- can this be an inner join instead?
SELECT
cd.PaperId
, COUNT(*) AS CodesF
FROM tbl_PaperCodes cd
GROUP BY
cd.PaperId
) cdd
ON cdd.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON c.ProviderId = p.ProviderId
INNER JOIN tbl_Sites s ON p.SiteId = s.SiteId
INNER JOIN tbl_Projects prr ON s.ProjectId = prr.ProjectId
INNER JOIN tbl_WFPaperEvents ev ON c.PaperId = ev.PaperId
INNER JOIN tbl_Users u ON ev.EventCreateUserId = u.UserId
INNER JOIN tbl_WFPaperEventTypes ett ON ev.EventId = ett.EventID
INNER JOIN tbl_WFPaperEventActions arr ON c.PaperId = arr.PaperId
AND ev.EventId = arr.EventId
INNER JOIN tbl_WFPaperEventActionResults ar ON arr.EventId = ar.EventID
AND arr.ActionResultId = ar.ResultID
AND arr.ActionResultId IN (1, 2, 3, 4)
LEFT OUTER JOIN (
SELECT
wfce.PaperEventActionNum
, wfce.PaperId
--, c.PaperId
--, CONVERT(varchar, wfce.ActionDate, 101) CompletionDate -- cast to date here
--, pr.ProjectName
--, wfce.ActionUserId
, u.firstname + ' ' + u.lastname [Editor]
FROM dbo.tbl_WFPaperEventActions wfce
--INNER JOIN dbo.tbl_Papers c ON wfce.PaperId = c.PaperId
--INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
--INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
--INNER JOIN tbl_Projects pr ON s.ProjectId = pr.ProjectId
tbl_Users INNER JOIN u ON wfce.ActionUserId = u.UserId
WHERE wfce.EventId = 204
AND c.Papersource = 0
GROUP BY
wfce.PaperEventActionNum
, wfce.PaperId
--, c.PaperId
--, CONVERT(varchar, wfce.ActionDate, 101)
--, pr.ProjectName
--, wfce.ActionUserId
, u.firstname + ' ' + u.lastname
) a
ON c.PaperId = a.PaperId AND arr.PaperEventActionNum = a.PaperEventActionNum
WHERE ev.EventCompletionDate >= DATEADD(DAY, DATEDIFF(DAY, 1, GETDATE()), 0)
AND ev.EventCompletionDate < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
AND ev.EventStatusId = 3
AND ev.EventId IN (201, 203)
AND c.Papersource = 0--Offshore
ORDER BY
paperid, u.FirstName + ' ' + u.LastName
I really do hate DISTINCT. It is nasty. It does not solve problems, it just hides them; AND slows down everything to do the hiding.
Use distinct in inverse proportion to query complexity:
if a query is really simple you can use distinct
If a query is complex do not use distinct
Check how many of fields on which you have join, where and group by clauses, have indexes. Every non-indexed field can negatively affect performance.
Calculated fields in GROUP BY are probably a pain, as well as DISTINCT (especially if they are not indexed). E.g. grouping on something like u.ID instead of u.firstname+' '+u.lastname or pr.ProjectId i/o pr.ProjectName should make things faster (you can sort the output according to the other criteria if needed).
Do you really need left join where you use it? I.e. do you want to keep the tables from the other side of the join even when there is no match on the other side? If not, replace it with inner join.
Various small improvements here, e.g.:
(assuming Papersource and EventId are indexes):
FROM
(SELECT * FROM dbo.tbl_WFPaperEventActions WHERE EventId = 204) wfce
INNER JOIN
(SELECT * FROM dbo.tbl_Papers WHERE Papersource = 0) c
ON wfce.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
INNER JOIN tbl_Projects pr ON s.ProjectId=pr.ProjectId
INNER JOIN tbl_Users u ON wfce.ActionUserId=u.UserId
instead of
FROM
dbo.tbl_WFPaperEventActions wfce
INNER JOIN dbo.tbl_Papers c ON wfce.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
INNER JOIN tbl_Projects pr ON s.ProjectId=pr.ProjectId
INNER JOIN tbl_Users u ON wfce.ActionUserId=u.UserId
WHERE
wfce.EventId = 204
AND c.Papersource =0
or (if I understood the idea correctly):
and ev.EventCompletionDate BETWEEN (
dateadd(day, -1, GETDATE()) and dateadd(ns, -1, GETDATE())
instead of:
and ev.EventCompletionDate >= dateadd(day,datediff(day,1,GETDATE()),0)
and ev.EventCompletionDate < dateadd(day,datediff(day,0,GETDATE()),0)
In general: ask yourself what exactly you want to achieve with this query, which parts of the data are relevant for it, how many of your source tables can be replaced with snippets from them (this can make JOINs work faster), and try to be consistent regarding the usage of JOIN and WHERE clauses.

Stored procedure for a select statement

I got a select statement. I want to add a join to this select statement and the join which I want to add is at the bottom of this code. why am I unable to add one more left outer join for this select statement? The join which I want to add is at the bottom. I also need to write a stored procedure for the entire select statement:
SELECT
FactId, UserType,
wr.WorkRequestId, wr.XerisUserKey,
xu.CsuserUserID UserId,
u.fname UserFName, u.lname UserLName,
b.PatientId, p.firstname PatFName, p.lastname PatLName,
GroupId, HospiceGroupKey GroupKey, WR.ContactKey,
C.ContactId, C.FirstName, C.LastName,
Convert(datetime, (Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay )) Start_dtm,
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay )) End_dtm,
DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay)),
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay ))) WRDuration,
(Convert(Decimal(18, 3), DATEDIFF(s, Convert(datetime,(Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay )),
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay ))))) *
(Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration,
CallBackNumber, WorkRequestType,
B.LineItemCount, ArchiveLocation, Processed,
ArchiveQueueType, TQA, Exclude, CallId
FROM
bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN
bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN
bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN
bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN
cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN
bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN
bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN
bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN
bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN
bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
WHERE
CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
This is the join I want to add to this select statement
left outer join
ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy (nolock) h on b.groupid = h.group_id
You are not allowed to call a table valued function remotely (ie across servers).
There is a workaround here:
Workaround for calling table-valued function remotely in SQL Server has even more issues
And more info here:
http://social.msdn.microsoft.com/Forums/en-US/1f0d2885-faa2-496a-b010-edc441260138/remote-tablevalued-function-calls-are-not-allowed?forum=transactsql

SQL / SSRS: The multi-part identifier " " could not be bound

Working on a report that currently is in two columns on two datasets, an dam trying to combine the datasets into one single query. When I do the following query, I get The multi-part identifier "fa.InternalUserID" could not be bound.
--TST Group
SELECT A.AuditID,
A.FileID,
A.Description,
A.UserID,
IU.FirstName + ' ' + IU.LastName AS UserName,
FM.FileNumber,
SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime',
CONVERT(VARCHAR(10), A.Date, 101) AS 'Date',
CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime',
COUNT(FA.FileActionsID) AS ActionCount
FROM FileMain fm
INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID
JOIN FileActions FA on FA.FileID = FM.FileID
LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID
WHERE (FM.OfficeID = 1)
AND (A.Description = 'File Opened'
OR A.Description = 'File Closed')
AND (A.Date >= GETDATE() - 2)
AND (IU.InternalUserID IN
(
--ID's go here
)
)
ORDER BY UserName, A.AuditID
Here are the original two queries I am combining:
--TST Group
SELECT A.AuditID,
A.FileID,
A.Description,
A.UserID,
IU.FirstName + ' ' + IU.LastName AS UserName,
FM.FileNumber,
SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime',
CONVERT(VARCHAR(10), A.Date, 101) AS 'Date',
CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime',
COUNT(FA.FileActionsID) AS ActionCount
FROM Audit AS A
INNER JOIN InternalUser AS IU ON A.UserID = IU.InternalUserID
LEFT OUTER JOIN FileMain AS FM ON A.FileID = FM.FileID
WHERE (FM.OfficeID = 1)
AND (A.Description = 'File Opened'
OR A.Description = 'File Closed')
AND (A.Date >= GETDATE() - 2)
AND (IU.InternalUserID IN
(
--ID's Go here
)
)
ORDER BY UserName, A.AuditID
and
SELECT IU.FirstName AS NAME,
COUNT(FA.FileActionsID) AS ActionCount
FROM FileActions AS FA
INNER JOIN InternalUser AS IU ON FA.ReceivedUserID = IU.InternalUserID
WHERE (FA.ReceivedDate > GETDATE() - 0)
AND (FA.ReceivedUserID IN (
--ID's go here
)
)
GROUP BY IU.FirstName
You have your joins in the wrong order. Currently you are trying to join InternalUser and FileActions when you've only mentioned FileMain and InternalUser (in that order) - you can't specify a condition against a table that hasn't been introduced to the join yet:
FROM FileMain fm
INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID
JOIN FileActions FA on FA.FileID = FM.FileID
LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID
Should be (with obligatory schema prefixes added):
FROM dbo.FileMain fm
INNER JOIN dbo.FileActions FA on FA.FileID = FM.FileID
INNER JOIN dbo.InternalUser AS IU ON FA.InternalUserID = IU.InternalUserID
LEFT OUTER JOIN dbo.Audit AS A ON A.FileID = FM.FileID

Categories