I have the below query -
select TeamProjectSK,
sum(case when d.System_State = 'Proposed' then 1 else 0 end) as New,
sum(case when d.System_State = 'Active' then 1 else 0 end) as Active,
sum(case when d.System_State = 'Resolved' then 1 else 0 end) as Resolved,
sum(case when d.System_State = 'Closed' then 1 else 0 end) as Closed
from
(
select w1.System_Id, w1.TeamProjectSK, w1.System_State, w1.System_Rev,
row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc) rn
from dbo.DimWorkItem w1
) d
where rn = 1
and d.System_Rev = (select max(w2.System_Rev) from dbo.DimWorkItem w2 where w2.System_Id = d.System_Id)
group by TeamProjectSK
order by TeamProjectSK desc;
The result of the query looks like -
TeamProjectSK New Active Resolved Closed
157 14 115 1 169
156 0 0 0 0
155 0 0 0 0
154 0 0 0 0
151 2 1 0 1
Now i want a column "Total_Count" which should be the sum of New+Active+Resolved+Closed. The output should look like -
TeamProjectSK Total_Count New Active Resolved Closed
157 289 14 115 1 169
156 0 0 0 0 0
155 0 0 0 0 0
154 0 0 0 0 0
151 4 2 1 0 1
I tried the below query, but it would not help. Please look into the same.
select TeamProjectSK,
New + Active + Resolved + Closed as Total_Count,
sum(case when d.System_State = 'Proposed' then 1 else 0 end) as New,
sum(case when d.System_State = 'Active' then 1 else 0 end) as Active,
sum(case when d.System_State = 'Resolved' then 1 else 0 end) as Resolved,
sum(case when d.System_State = 'Closed' then 1 else 0 end) as Closed
from
(
select w1.System_Id, w1.TeamProjectSK, w1.System_State, w1.System_Rev,
row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc) rn
from dbo.DimWorkItem w1
) d
where rn = 1
and d.System_Rev = (select max(w2.System_Rev) from dbo.DimWorkItem w2 where w2.System_Id = d.System_Id)
group by TeamProjectSK
order by TeamProjectSK desc;
Regards.
select TeamProjectSK, New + Active + Resolved + Closed as Total_Count, New Active, Resolved, Closed
from
(
select TeamProjectSK,
sum(case when d.System_State = 'Proposed' then 1 else 0 end) as New,
sum(case when d.System_State = 'Active' then 1 else 0 end) as Active,
sum(case when d.System_State = 'Resolved' then 1 else 0 end) as Resolved,
sum(case when d.System_State = 'Closed' then 1 else 0 end) as Closed
from
(
select w1.System_Id, w1.TeamProjectSK, w1.System_State, w1.System_Rev,
row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc) rn
from dbo.DimWorkItem w1
) d
where rn = 1
and d.System_Rev = (select max(w2.System_Rev) from dbo.DimWorkItem w2 where w2.System_Id = d.System_Id)
group by TeamProjectSK
) a
order by TeamProjectSK desc
Related
I am using a sql query but sorry to say unable to use a where condition. I post my query below.
SELECT * , CAST( RIGHT(FileNo,3) AS numeric) as IntFileNo
FROM ExportLcs A
OUTER APPLY (
SELECT SUM(ReceivedTTUsd) AS TtTotal,
SUM(ReceivedPDCUsd) AS PdcTotal,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal,
SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd,
Count(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments G
WHERE A.ExportLcId = G.ExportLcId AND (G.PdcTotal+G.PdcTotalUsd)>0
) AS G
I want to use condition like
A.ExportLcId = G.ExportLcId AND (G.PdcTotal+G.PdcTotalUsd)>0
but and part not working.
Any one can help.
How about having clause instead of where?
SELECT * , CAST(RIGHT(FileNo, 3) AS NUMERIC) AS IntFileNo
FROM dbo.ExportLcs AS A
OUTER APPLY (
SELECT SUM(ReceivedTTUsd) AS TtTotal
, SUM(ReceivedPDCUsd) AS PdcTotal
, SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount
, SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal
, SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd
, COUNT(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments AS G
WHERE A.ExportLcId = G.ExportLcId
HAVING (SUM(ReceivedPDCUsd) + SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END)) > 0
) AS G;
You should consider using Outer Join instead, so try the following:
SELECT * , CAST( RIGHT(FileNo,3) AS numeric) as IntFileNo from ExportLcs A left outer join
(
SELECT SUM(ReceivedTTUsd) AS TtTotal,
SUM(ReceivedPDCUsd) AS PdcTotal,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal,
SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd,
Count(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments) G
on A.ExportLcId = G.ExportLcId where (G.PdcTotal+G.PdcTotalUsd)>0
just put your part where clause outside.
SELECT * , CAST( RIGHT(FileNo,3) AS numeric) as IntFileNo
FROM Export
where (G.PdcTotal+G.PdcTotalUsd)>0Lcs A
OUTER APPLY (
SELECT SUM(ReceivedTTUsd) AS TtTotal,
SUM(ReceivedPDCUsd) AS PdcTotal,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal,
SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd,
Count(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments G
WHERE A.ExportLcId = G.ExportLcId
) AS G
I have this query that returns 1 row of aggregate sums
DECLARE #Income9 int
SELECT #Income9 = IncomeLevel FROM PovertyLevels WHERE HouseholdNumber = 9
;WITH CTE
AS
(
SELECT PatientProfileID, CASE WHEN v.FamilyMembersinHousehold > 8
THEN ROUND((CAST(AnnualIncome as float)/(CAST(#Income9 as float) +((V.FamilyMembersinHousehold-8)* CAST(#Income9 as Float)))*100.00), 5)
WHEN ((v.FamilyMembersinHousehold IS NULL) OR (AnnualIncome IS NULL)) THEN NULL
ELSE ROUND(((CAST(AnnualIncome AS Float)/CAST(pl.IncomeLevel as Float)) * 100.00), 5) END AS PercentOfPoverty
FROM vPatientDemographics v
LEFT OUTER JOIN PovertyLevels pl ON v.FamilyMembersinHousehold = pl.HouseholdNumber
)
SELECT SUM(CASE WHEN PercentOfPoverty <= 100 THEN 1 ELSE 0 END) AS NumOfPatientsBelow100,
SUM(CASE WHEN PercentOfPoverty BETWEEN 101 AND 150 THEN 1 ELSE 0 END) AS NumOfPatientsBetween101And150,
SUM(CASE WHEN PercentOfPoverty BETWEEN 151 AND 200 THEN 1 ELSE 0 END) AS NumOfPatientsBetween151And200,
SUM(CASE WHEN PercentOfPoverty > 200 THEN 1 ELSE 0 END) AS NumOfPatientsOver200,
SUM(CASE WHEN PercentOfPoverty IS NULL THEN 1 ELSE 0 END) AS NumOfPatientsUnknown
FROM CTE
I would like to have the sum data to be in rows not columns.
I tried adding this UNPIVOT but it does not recognize the column names.
UNPIVOT
(
Levels for PovertyLevels in (NumOfPatientsBelow100, NumOfPatientsBetween101And150, NumOfPatientsBetween151And200,
NumOfPatientsOver200, NumOfPatientsUnknown)
) as Unpvt
How can I unpivot the initial data set to that it is in rows not columns?
It is because Where clause is evaluated before the select
SELECT #Income9 = IncomeLevel FROM PovertyLevels WHERE HouseholdNumber = 9
;WITH CTE
AS
(
SELECT PatientProfileID, CASE WHEN v.FamilyMembersinHousehold > 8
THEN ROUND((CAST(AnnualIncome as float)/(CAST(#Income9 as float) +((V.FamilyMembersinHousehold-8)* CAST(#Income9 as Float)))*100.00), 5)
WHEN ((v.FamilyMembersinHousehold IS NULL) OR (AnnualIncome IS NULL)) THEN NULL
ELSE ROUND(((CAST(AnnualIncome AS Float)/CAST(pl.IncomeLevel as Float)) * 100.00), 5) END AS PercentOfPoverty
FROM vPatientDemographics v
LEFT OUTER JOIN PovertyLevels pl ON v.FamilyMembersinHousehold = pl.HouseholdNumber
),intr as
(
SELECT SUM(CASE WHEN PercentOfPoverty <= 100 THEN 1 ELSE 0 END) AS NumOfPatientsBelow100,
SUM(CASE WHEN PercentOfPoverty BETWEEN 101 AND 150 THEN 1 ELSE 0 END) AS NumOfPatientsBetween101And150,
SUM(CASE WHEN PercentOfPoverty BETWEEN 151 AND 200 THEN 1 ELSE 0 END) AS NumOfPatientsBetween151And200,
SUM(CASE WHEN PercentOfPoverty > 200 THEN 1 ELSE 0 END) AS NumOfPatientsOver200,
SUM(CASE WHEN PercentOfPoverty IS NULL THEN 1 ELSE 0 END) AS NumOfPatientsUnknown
FROM CTE
)
Select cnt,range from intr
cross apply (values (NumOfPatientsBelow100,'NumOfPatientsBelow100'),
(NumOfPatientsBetween101And150,'NumOfPatientsBetween101And150'),
(NumOfPatientsBetween151And200,'NumOfPatientsBetween151And200'),
(NumOfPatientsOver200,'NumOfPatientsOver200'),
(NumOfPatientsUnknown,'NumOfPatientsUnknown')) cs (cnt,range)
I need to add the number of records in which the status is set to 'reopened'. But the 'reopened' status has several IDs.
This is the subquery that will Id the 'reopen' statuses:
SELECT (CASE WHEN s.sr_status_recid = 1 THEN 1 ELSE 0 END) AS Reopened
from v_rpt_service s
where vsrv.sr_status_recid in
(select distinct SR_Status_RecID from SR_Status where [Description] like '%Re-opened%'))
This is the main query that the above query needs to be a part:
SELECT DATEPART(WK, vsrv.date_entered) as WkNumber,
COUNT(vsrv.TicketNbr) AS OpenedIssues, --total ticket count
SUM(CASE WHEN vsrv.Closed_Flag = 1 THEN 1 ELSE 0 END) AS ClosedIssues, --sum of tickets with closed_flag = 1
(SELECT SUM(CASE WHEN s.sr_status_recid = 1 THEN 1 ELSE 0 END)
from v_rpt_service s
where vsrv.sr_status_recid in
(select distinct SR_Status_RecID from SR_Status where [Description] like '%Re-opened%')) AS ReopenedIssues,
SUM(CASE WHEN vsrvy.Surveys_Completed = 1 THEN 1 ELSE 0 END) AS SurveysCompletedWithConnectWise, -- Surveys_Completed flag in view is 1
SUM(CASE WHEN Source = 'Portal' THEN 1 ELSE 0 END) AS IssueLoggedPortal,
SUM(CASE WHEN Source = 'Email Connector' THEN 1 ELSE 0 END) AS IssueLoggedEmai
FROM v_rpt_service vsrv LEFT OUTER JOIN v_rpt_SurveysByTicket vsrvy ON vsrv.TicketNbr = Vsrvy.SR_Service_RecID
WHERE vsrv.company_name <> 'XYZ Test Company' AND vsrv.date_entered BETWEEN '01/01/2016' AND '10/07/2016'
GROUP BY DATEPART(WK, vsrv.date_entered)
ORDER BY WkNumber
How can I have a subquery that uses a CASE statement and the CASE statement is aggregated?
You can use CROSS APPLY
SELECT DATEPART(WK, vsrv.date_entered) as WkNumber,
COUNT(vsrv.TicketNbr) AS OpenedIssues, --total ticket count
SUM(CASE WHEN vsrv.Closed_Flag = 1 THEN 1 ELSE 0 END) AS ClosedIssues, --sum of tickets with closed_flag = 1
SUM(CountReopen.YesNo) AS NumberOfReopen,
SUM(CASE WHEN vsrvy.Surveys_Completed = 1 THEN 1 ELSE 0 END) AS SurveysCompletedWithConnectWise, -- Surveys_Completed flag in view is 1
SUM(CASE WHEN Source = 'Portal' THEN 1 ELSE 0 END) AS IssueLoggedPortal,
SUM(CASE WHEN Source = 'Email Connector' THEN 1 ELSE 0 END) AS IssueLoggedEmail
FROM v_rpt_service vsrv
LEFT OUTER JOIN v_rpt_SurveysByTicket vsrvy
ON vsrv.TicketNbr = Vsrvy.SR_Service_RecID
CROSS APPLY (
SELECT IIF(COUNT(*) > 0,1,0) YesNo
FROM SR_Status
where [Description] like '%Re-opened%'
AND SR_Status_ID = vsrv.sr_status_recid
) CountReopen(YesNo)
WHERE vsrv.company_name <> 'XYZ Test Company'
AND vsrv.date_entered BETWEEN '01/01/2016' AND '10/07/2016'
GROUP BY DATEPART(WK, vsrv.date_entered)
ORDER BY WkNumber
I have the following Access query that needs turned into SQL -
TRANSFORM
Sum([anaes_downtime]![ANAESENDTIME]-[anaes_downtime]![anaesstarttime])/24/60 AS Expr1
SELECT downtime_seq.THEATRE, downtime_seq.OPSESSION, downtime_seq.OPDATE
FROM ANAES_Downtime
INNER JOIN downtime_seq ON ANAES_Downtime.opnumber = downtime_seq.opnumber
WHERE (((ANAES_Downtime.ANAESSTARTTIME) <> 0 )
AND ((ANAES_Downtime.ANAESENDTIME) <> 0 ))
GROUP BY downtime_seq.THEATRE, downtime_seq.OPSESSION, downtime_seq.OPDATE
PIVOT "d" & [opseq] IN ("d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","d10","d11","d12","d13","d14","d15","d16","d17","d18","d19","d20");
I understand the basics of sql pivot but have been unable to convert this successfully. Any help?
I have found an answer to my question using the CASE statement -
SELECT ad.THEATRE, ad.OPSESSION, ad.OPDATE,
SUM(CASE WHEN opseq = 0
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd0',
SUM(CASE WHEN opseq = 1
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd1',
SUM(CASE WHEN opseq = 2
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd2',
SUM(CASE WHEN opseq = 3
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd3',
SUM(CASE WHEN opseq = 4
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd4',
SUM(CASE WHEN opseq = 5
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd5'...
...FROM #ANAES_Downtime ad INNER JOIN #DowntimeSeq ds ON ad.opnumber = ds.opnumber
WHERE ad.ANAESSTARTTIME <> 0 AND ad.ANAESENDTIME <> 0
GROUP BY ad.THEATRE, ad.OPSESSION, ad.OPDATE
ORDER BY ad.THEATRE, ad.OPSESSION, ad.OPDATE
The TotalScore result is 320 when it should just be 80(30 + 50) since the top 1 record for ProviderID 874 has SessionsProgress = 3 and the providerID is also present in the joined SubscriptionsTV table.
DECLARE #ProviderID int = '874';
WITH cte as(
SELECT TOP 1 a.ProviderID, Time_Stamp,
SUM(CASE WHEN [AdditionalReports] = '1' THEN 5 ELSE 0 END) as AdditionalReports,
SUM(CASE WHEN [UniqueReportRequests] = '1' THEN 15 ELSE 0 END) as UniqueReportsRequests,
SUM(CASE WHEN [SessionsProgress] > '0' THEN 30 ELSE 0 END) as SessionsProgress,
MAX(CASE WHEN b.ProviderID IS NULL THEN 0 ELSE 50 END) as SubscriptionExists
FROM ProviderValueCard a
LEFT JOIN SubscriptionsTV b
ON a.ProviderID = b.ProviderID
WHERE a.ProviderID = #ProviderID AND GroupID = 2
GROUP BY Time_Stamp, a.ProviderID, event
ORDER BY event DESC, Time_Stamp DESC
)
SELECT ProviderID, Time_Stamp, (AdditionalReports + UniqueReportsRequests + SessionsProgress + SubscriptionExists) AS TotalScore
FROM cte
Here are the 2 records for ProviderID 874 which only the most recent by TimeStamp is used.
ProviderID AdditionalReports UniqueReportRequests Time_Stamp AdditionalReportsNum UniqueReportsNum SessionsProgress AdditionalReportsNumQtr UniqueReportsNumQtr SurveyCompleted
----------- ----------------- -------------------- ----------------------- -------------------- ---------------- ---------------- ----------------------- ------------------- ---------------
874 0 1 2015-01-30 08:13:44.660 0 55 3 0 10 1
874 0 0 2014-12-30 08:31:20.893 0 0 3 0 0 1