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)
Related
I want to separate the morning and evening patient checked-in count gender-wise and also if gender age less then show the Female child and M child on the basis of gender.
SELECT
COUNT(ch.EnteredOn) AS counter,
CONVERT(date, ch.EnteredOn) AS sessionDay,
SUM(CASE WHEN CAST(CONVERT(CHAR(2), ch.EnteredOn, 108) AS INT) < 12 THEN 1 ELSE 0 END) AS 'Morning',
SUM(CASE WHEN CAST(CONVERT(CHAR(2), ch.EnteredOn, 108) AS INT) >= 12 THEN 1 ELSE 0 END) AS 'Evening',
SUM(CASE WHEN p.Gender = 1 THEN 1 ELSE 0 END) AS Male,
SUM(CASE WHEN p.Gender = 2 THEN 1 ELSE 0 END) AS Fmale,
SUM(CASE WHEN DATEDIFF(hour, P.DOB, GETDATE()) / 8766 <= 18
AND P.Gender = 1 THEN 1 ELSE 0 END) AS MChild,
SUM(CASE WHEN DATEDIFF(hour, P.DOB, GETDATE()) / 8766 <= 18
AND P.Gender = 2 THEN 1 ELSE 0 END) AS FChild
FROM
Patient.CheckIn ch
INNER JOIN
Patient.Patients P ON ch.PatientId = p.PatientId
GROUP BY
Ch.EnteredOn
I have only three columns like Gender, Time and DOB. Gender id 1 shows the male and Gender id 2 is using for females.
enter image description here
SELECT convert(date, ch.EnteredOn) AS sessionDay, CAST( CONVERT(CHAR(2), ch.EnteredOn, 108) AS INT) <12 as morning, count(ch.EnteredOn) AS counter
,sum(case when p.Gender=1 Then 1 ELSE 0 end) as Male
,sum(case when p.Gender=2 Then 1 ELSE 0 end) as Fmale
,Sum( case when DATEDIFF(hour,P.DOB,GETDATE())/8766<=18 AND P.Gender=1 Then 1 ELSE 0 end ) as MChiled
,Sum( case when DATEDIFF(hour,P.DOB,GETDATE())/8766<=18 AND P.Gender=2 Then 1 ELSE 0 end ) as FChiled
FROM Patient.CheckIn ch
inner join Patient.Patients P on ch.PatientId=p.PatientId
Group by Ch.EnteredOn
Group BY can be
Group by convert(date, ch.EnteredOn) AS sessionDay, CAST( CONVERT(CHAR(2), ch.EnteredOn, 108) AS INT) <12
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 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
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