SQL: How to get COUNT when using EXCEPT - sql

SELECT 'COUNT=' + CONVERT(VARCHAR(64), COUNT(s.company)) AS sites
FROM site s
WHERE s.sitetype = 'om'
AND s.status = 1
EXCEPT
SELECT DISTINCT sg.company
FROM snmpmibdevice AS sdevice
JOIN site sg
ON sg.guid = sdevice.siteguid
JOIN snmpmibdata sdata
ON sdata.snmpmibdeviceguid = sdevice.snmpmibdeviceguid
WHERE sdata.sampletimestamp > Dateadd (mi, -15, Getutcdate())
AND sg.sitetype = 'OM'
Basically I am attempting to return a count of company names from this. If I remove the count and just select "S.Company" I will get 2 values (I would like "COUNT=2"), but with the count it comes up as 34 records (COUNT=34).
I would appreciate any help. Thanks!

wrap the whole thing in a "select count(*) from ()"
SELECT 'COUNT=' + CONVERT(VARCHAR(64), COUNT(company)) AS sites
FROM (
SELECT s.company
FROM site s
WHERE s.sitetype = 'om'
AND s.status = 1
EXCEPT
SELECT DISTINCT sg.company
FROM snmpmibdevice AS sdevice
JOIN site sg
ON sg.guid = sdevice.siteguid
JOIN snmpmibdata sdata
ON sdata.snmpmibdeviceguid = sdevice.snmpmibdeviceguid
WHERE sdata.sampletimestamp > Dateadd (mi, -15, Getutcdate())
AND sg.sitetype = 'OM'
) a

Related

SQL left join returns nothing when no matches

I am writing a stored procedure that adds the counts to two fields. I have the following code:
SELECT Distinct DateTime1,SUM(TICKETREQ1)SUMREQ, SUM(TicketPU1)SUMPU1, (count(*))AS GRADCOUNT
FROM TABLEA
WHERE YEAR = '2015'
AND TicketReq1 > 0
group by DateTime1
Select DISTINCT(DateTime2),SUM(TicketReq2) SUMREQ,SUM(TicketPU2)SUMPU2, (count(*))AS GRADCOUNT
from TABLEA
where TicketReq2 > 0
and YEAR = '2015'
Group by DateTime2;
SELECT Distinct c.DateTime1,SUM(c.TICKETREQ1 + b.TicketReq2)SUMREQ, SUM(c.TicketPU1 + b.TicketPU2)SUMPU1, (count(b.id) + count(c.id))AS GRADCOUNT
FROM TABLEA c
LEFT JOIN TABLEA b
ON (b.DateTime2 = c.DateTime1
AND b.TicketReq2 > 0
AND b.YEAR = '2015')
WHERE c.YEAR = '2015'
AND c.TicketReq1 > 0
group by c.DateTime1
This returns:
For some ceremonies the second query does bring in results and adds them correctly. But if there are no records then it fails.
How can I get it to join the two counts together (Query 1 and 2) so that Query 3 displays both counts even when there is no match
The problem is the SUM statements on query #3. b.TicketReq2 is null, therefore SUM(c.TICKETREQ1 + b.TicketReq2) should encounter an error. Try using ISNULL(b.TicketReq2, 0) in your SUM function calls.
Try full outer join instead of left join
SELECT Distinct c.CeremonyDateTime1,SUM(c.TICKETREQ1 + b.TicketReq2)SUMREQ, SUM(c.TicketPU1 + b.TicketPU2)SUMPU1, (count(b.gid) + count(c.gid))AS GRADCOUNT
FROM ComTicket c
FULL OUTER JOIN ComTicket b
ON (b.CeremonyDateTime2 = c.CeremonyDateTime1
AND b.TicketReq2 > 0
AND b.Gradterm = '201540')
WHERE c.gradterm = '201540'
AND c.TicketReq1 > 0
group by c.CeremonyDateTime1
It might helpful to you..

SQL Random Item for each USER

I have been searching and cannot find the right way to do this. In my query below, What I need is one random C.CREDENTIALING_K for each U.USER_K. I know the newid() will be needed somewhere, I just cannot find the proper place to put it.
select
U.USER_K,
U.FULLNAME as 'Chg_By',
CONVERT(DATE,AL.AUDITDATETIME) as 'Verif_Date',
P.ID,
P.LONGNAME,
CONVERT(DATE,P.DATEOFBIRTH) as 'DOB',
C.entity_k,
R.DESCRIPTION as 'CVI_TYPE',
C.CREDENTIALING_K,
CG.GROUPDESCRIPTION,
C.APPLICATION_RECEIVED,
R1.DESCRIPTION as 'Cur_STATUS',
CONVERT(DATE,C.USERDEF_D3) as 'MSO_DUE_DT'
from
VisualCACTUS.AUDITLOG AL
JOIN VisualCACTUS.USERS U
on U.user_k = AL.USER_K
join VisualCACTUS.CREDENTIALING C
JOIN VisualCACTUS.PROVIDERS P
on P.provider_k = C.PROVIDER_K
JOIN visualcactus.CREDENTIALINGGROUP CG
on CG.CREDENTIALINGGROUP_K = C.CREDENTIALINGGROUP_K
JOIN VisualCACTUS.REFTABLE R
on R.reftable_k = CG.TYPE_RTK
JOIN VisualCACTUS.REFTABLE R1
ON R1.REFTABLE_K = C.CREDENTIALINGSTATUS_RTK
--JOIN VisualCACTUS.CREDENTIALINGASSIGNMENTS CA
--on CA.credentialing_k = CA.credentialing_k
on C.CREDENTIALING_K = AL.FILE_PRIMARYKEY
where
AUDITLOG_K in (select AUDITLOG_K from VisualCACTUS.AUDITLOG_RECORDLEVEL where TABLE_NAME = 'CREDENTIALING '
and
AUDITLOG_RECORDLEVEL_K in (SELECT AUDITLOG_RECORDLEVEL_K from VisualCACTUS.AUDITLOG_FIELDLEVEL where NEWVALUE_SHORT = 'D2680X38F3'))
and
C.USERDEF_L1 = 0
and
CG.TYPE_RTK NOT IN ('D2870MPPSO','D2LC0YR0AR','D2DD1EIY5X')
and
CG.TYPE_RTK NOT LIKE ('SSP%')
and
C.credentialing_k not in (select credentialing_k from VisualCACTUS.CREDENTIALINGASSIGNMENTS where EA_K in (select ea_k from visualcactus.entityassignments where entity_k in ('HCA0000039',
'HCA0000040',
'HCA0000041',
'HCA0000043',
'HCA0000096',
'HCA0000095',
'HCA0000337',
'HCA0000903',
'HCA0000904',
'HCA0000905',
'HCA0000906',
'HCA0000080')))
and
CONVERT(DATE, AUDITDATETIME) = DATEADD(day, -1, convert(date, GETDATE()))
order by 'Chg_By'
Make a correlated subquery to return random CREDENTIALING_K
CREDENTIALING_K=(select top 1 C1.CREDENTIALING_K
from VisualCACTUS.CREDENTIALING c1
Where P.provider_k = C1.PROVIDER_K
order by newid())
Note : If needed add the filter that you have used for VisualCACTUS.CREDENTIALING table inside subquery too

Query to return all values in a specific table column

The query below returns a somatory of all groups in the year.
How can I return all groups that exists in IND_GRUPO but grouped by the month, if doesn't exist the group for the current month, the name should appear, but the somatory will be 0. All joins should be kept.
SELECT SUM(p.valor), c.nm_grupo, c.cd_grupo, YEAR(p.dt_emissao)
FROM ind_receita p
JOIN ind_equipto o ON p.cd_equipto = o.cd_equipto
JOIN ind_grupo c ON o.cd_grupo = c.cd_grupo
WHERE YEAR(p.dt_emissao) = YEAR(GETDATE())
GROUP BY YEAR(p.dt_emissao), c.nm_grupo, c.cd_grupo
ORDER BY 1 DESC
Try this:
SELECT c.nm_grupo, c.cd_grupo, YEAR(GETDATE()),
(SELECT SUM(p.valor)
FROM ind_receita p
JOIN ind_equipto o ON p.cd_equipto = o.cd_equipto
JOIN ind_grupo c2 ON o.cd_grupo = c2.cd_grupo
WHERE c2.cd_grupo = c.cd_grupo
AND YEAR(p.dt_emissao) = YEAR(GETDATE())) AS valor
FROM ind_grupo c

Remove duplicate rows in t-sql query results

I have a some T-SQL below and i am facing a problem where each row is being returned twice with the same values. How can ensure each is returned once or force a select Distinct
;WITH CTE_ReportDetails
AS (
SELECT
CASE(GROUPING(M.Acronym))
WHEN 0 THEN [Acronym]
WHEN 1 THEN 'GRAND TOTAL'
END AS [Company],
CASE(GROUPING(DC.Name))
WHEN 0 THEN DC.[Name]
WHEN 1 THEN 'N/A'
END AS [CatName],
CASE(GROUPING(D.[Name]))
WHEN 0 THEN D.[Name]
WHEN 1 THEN 'Total '+ '('+DC.[Name]+')'
END AS [Name],
SUM(ISNULL(B.One, 0)) AS One,
SUM(ISNULL(B.Two, 0)) AS Two,
SUM(ISNULL(B.Three, 0)) AS Three,
ISNULL(B.Description, '') AS Description,
GROUPING(M.Acronym) AS CompanyGrouping,
GROUPING(DC.[Name]) AS DCatGroup,
GROUPING(D.[Name]) AS DGroup
FROM Dee D
INNER JOIN DeeCategory DC ON D.DeeCategoryId = DC.DeeCategoryId
INNER JOIN BD B ON B.DeeId = D.DeeId
INNER JOIN Report R ON R.RptId = B.RptId
INNER JOIN Company M ON R.CompanyId = M.CompanyId
WHERE (R.ReportDate >= #StartDate AND R.ReportDate <= #EndDate) AND (R.CompanyId IN (SELECT DATA FROM SPLIT(#CompanyIds,',')))
GROUP BY M.Acronym, DC.Name, D.Name,B.Description
WITH ROLLUP
)
SELECT Company, Name As [Dee],
One,
Three,
Two,
(One + Three + Two) AS Total,
Description
FROM CTE_ReportDetails
Your report should have a unique combinations of values from the group by. So, these four columns should be unique:
GROUP BY M.Acronym, DC.Name, D.Name,B.Description
If I had to guess, you are getting duplicates because B.Description is duplicated in the B table. I would suggest removing it from the GROUP BY and changing this line:
ISNULL(B.Description, '') AS Description,
to
ISNULL(max(B.Description), '') AS Description,

SQL select where date is a week or younger

I need to select records that are a week or less in age, by this column: dbo.mod_employmentAppProfile.dateSubmitted
Note, the #arguments.departmentID# is a coldfusion tag.
Here's my query:
SELECT
dbo.pro_Profile.profileID,
dbo.pro_Profile.firstName,
dbo.pro_Profile.lastName,
dbo.pro_Profile.isDeleted,
dbo.pro_Email.emailAddress,
dbo.mod_employmentAppJobTitles.supervisorID,
dbo.mod_employmentAppJobs.appID,
dbo.mod_employmentAppJobs.isRejected,
dbo.mod_employmentAppJobs.isDeleted AS isDeletedJobs,
dbo.mod_employmentAppJobs.emailSent,
dbo.mod_employmentAppProfile.dateAvailable,
dbo.mod_employmentAppProfile.dateSubmitted,
dbo.mod_employmentAppProfile.firstName AS appFirstName,
dbo.mod_employmentAppProfile.lastName AS appLastName,
dbo.mod_employmentAppJobTitles.title,
dbo.mod_employmentAppProfile.name,
dbo.mod_employmentAppProfile.phone,
dbo.mod_employmentAppProfile.major,
dbo.mod_employmentAppProfile.minor
FROM dbo.pro_Email
INNER JOIN dbo.pro_Profile
ON dbo.pro_Email.profileID = dbo.pro_Profile.profileID
INNER JOIN dbo.mod_employmentAppJobs
INNER JOIN dbo.mod_employmentAppJobTitles
ON dbo.mod_employmentAppJobs.jobTitleID = dbo.mod_employmentAppJobTitles.jobTitleID
INNER JOIN dbo.mod_employmentAppProfile
ON dbo.mod_employmentAppJobs.eAppID = dbo.mod_employmentAppProfile.eAppID
ON dbo.pro_Profile.profileID = dbo.mod_employmentAppJobTitles.supervisorID
WHERE (dbo.mod_employmentAppJobs.emailSent = 0)
AND (dbo.mod_employmentAppJobTitles.departmentID = #arguments.departmentID#)
AND (dbo.mod_employmentAppJobs.isRejected = 0)
I did try something like:
and (dbo.mod_employmentAppProfile.dateSubmitted < DATEADD(day, - 7, GETDATE()))
which returns no results.
Suggestions?
try
(dbo.mod_employmentAppProfile.dateSubmitted > DATEADD(day, -7, GETDATE()))