I'm using SQL Server 2005. I'm looking to add up the columns (AM, Midday, Evening) to see which ones contains the value "YES" and then take that total and multiply it by the rate for each row for a client.
Here is the query I have so far:
Select
Sum(Case When morning = 'yes' Then 1 Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 Else 0 End) midday_total
From services
where client_id = 24
with the following output
am_total midday_total
45 49
When I introduce the rate variable, my query starts telling me I need the group_by clause and I don't think I'm ready for that since I still need to add the am_total and the midday_total together first and then multiply that by the rate.
Ultimately, all I'm looking for is the grand total.
If I understand your question, maybe this is what you need
declare #rate int
set #rate = 2 /*what ever rate is */
select am_total * #rate as am, midday_total * #rate as midday
from (
Select
Sum(Case When morning = 'yes' Then 1 Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 Else 0 End) midday_total
From services
where client_id = 24
)
You can also join another table and use its columns in calculation
Select
Sum(Case When morning = 'yes' Then 1 * u.rate Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 * u.rate Else 0 End) midday_total
From services srv inner join users u on services.id = u.service_id -- assuming this is relation
pay attention on u.rate above
Related
I have a table like this:
I would like to get the distinct counts for every GROUP:
How to get the result? Thank you.
You can use conditional aggregation:
select group,
sum(case when location = 'A' then 1 else 0 end) as a,
sum(case when location = 'B' then 1 else 0 end) as b,
sum(case when location = 'C' then 1 else 0 end) as c
from t
group by group;
Note that group is a very poor name for a column because it is a SQL reserved word.
I am attempting to get the total of the meters for each type along with the estimated meters for each type, but the total does not come in correctly.
SELECT AMI_YEAR, AMI_MONTH,
COUNT(ACCOUNT_NO) as TOTal_Bills,
SUM(CASE WHEN Device_Type = 'AMI' THEN 1 ELSE 0 END) + SUM(CASE WHEN Device_Type = 'OTHER' THEN 1 ELSE 0 END) AS Total_Estimated,
SUM(CASE WHEN Device_Type = 'AMI' THEN 1 ELSE 0 END) AS
AMI_Estimated,
SUM(CASE WHEN Device_Type = 'OTHER' THEN 1 ELSE 0 END) AS
NON_AMI_Estimated
FROM
(SELECT DISTINCT
A.GL_PERIOD AS AMI_MONTH,
A.GL_YEAR AS AMI_YEAR,
A.ACCOUNT_NO,
CASE WHEN X.DEVICE_TP = 'AMI' THEN 'AMI' ELSE 'OTHER' END
AS Device_Type
FROM A
INNER JOIN B ON A.ACCOUNT_NO = B.ACCOUNT_NO AND CONVERT(DATE,A.BILL_RUN_DT,101) = CONVERT(DATE,B.BILL_RUN_DT,101)
INNER JOIN C ON A.ACCOUNT_NO = C.ACCOUNT_NO AND A.LOCATION_NO = C.LOCATION_NO AND CONVERT(DATE,A.BILL_RUN_DT,101) = CONVERT(DATE,C.BILLED_DTM,101)
LEFT OUTER JOIN X ON C.SERIAL_NO =
X.DEVICE_SERIAL_NO
WHERE A.ESTIMATED_YN = 'T'
AND A.GL_YEAR >= YEAR(GETDATE())-1
AND B.VOIDED_YN = 'F'
)Z
GROUP BY AMI_YEAR, AMI_MONTH
ORDER BY AMI_YEAR, AMI_MONTH
will return all the information for estimated meters, but not the total of the meters, ex for one row:
Year, AMI_MONTH, Total_BILLS, TOTAL_ESTIMATED, AMI_ESTIMATED, NON_AMI ESTIMATED
2017, 1, 695, 695, 0, 695
I also need the total of ami meters and a total of non_ami meters (estimated + non estimated for each type). When I try to add something like: DEVICE_TYPE, COUNT (*) AS TYPE to the main or the sub query it fails.
How do I get the current results and the total of all ami and all non-ami meters? An over-all total for each type would be nice too, but can be computed easily enough.
I have data for my Student in my lookupdata table (Enrolled, Droped Out, Canclled, all with ldTypeID = 129). The rest of my data is stored in vStudent. I need to write proc which will give me a report of all my Student, the Male and Female but per different Country. Where did I go wrong with my code?
Student Status Total Number Total # Males Total # Females
Enrolled
Dropped Out
Cancelled
Graduated
CREATE PROCEDURE [dbo].[pr_ReportPerCountry]
#CountryID int
AS
DELETE FROM ReportData WHERE rdTypeID = 2
INSERT INTO ReportData
(
rdSortBy,
rdTypeID,
rdName1,
rdValue1,
rdValue2,
rdValue3,
)
Select
0 AS SoryBy,
2 AS rdTypeID,
finalStudentStatus,
sum (case when peFinalStatusID in (303) then 1 else 0 end) as TotalEnrolled,
sum(case when (peFinalStatusID in (303) and peSexID=7) then 1 else 0 end) as MaleEnrolled,
sum(case when (peFinalStatusID in (303) and peSexID=8) then 1 else 0 end) as FemaleEnrolled
from vStudentPerson
left join (SELECT ldLookupDataID,ldValue FROM LookupData
WHERE ldTypeID = 129
group by ldLookupDataID,ldValue
) sta on peFinalStatusID=sta.ldLookupDataID
WHERE peFinalStatusID in (297,298,299,303) and peCountryofResidencyID = 0 or peCountryofResidencyID=#CountryID
I find solution, thanks anyway.
INSERT INTO ReportData
(
rdSortBy,
rdTypeID,
rdName1,
rdValue1,
rdValue2,
rdValue3
)
Select
0 AS SoryBy,
1 AS rdTypeID,
academicYear,
count (pePersonID) as TotalAwarded,
sum (case when peSexID = 7 then 1 else 0 end ) as TotalAwardedMale,
sum (case when peSexID = 8 then 1 else 0 end ) as TotalAwardedFemale
from vStudentPerson
left join (SELECT * FROM vStudentPersonScholarship) sch on pePersonID=sch.psPersonID
where (#CountryID = -1 or peCountryofResidencyID = #CountryID) and psScholarahipRenewalsTypeID=281
group by sch.academicYear
I have a SQL statement that has multiple case statements like the below:
SUM(CASE [Type]
WHEN 418
THEN CASE WHEN PMTS.DateCreated BETWEEN #sd AND #ed
AND( PMTS.Amount >0 OR PMTS.Mileage >0)
AND PMTS.PaymentEventID = 0 THEN Mileage END
ELSE 0 END) AS DriverMileage
But I need the result of the sum to set a variable and use that in the where in the WHERE clause.
Example below
DECLARE #contribution decimal
SElECT PMTS.VolunteerId ,
SET #contribution = SUM(CASE [Type]
WHEN 1003
THEN CASE WHEN PMTS.DateCreated BETWEEN #sd AND #ed
AND( PMTS.Amount >0 OR PMTS.Mileage >0)
AND PMTS.PaymentEventID = 0
THEN Amount END
ELSE 0 END) AS GPContributions
FROM PMTS WHERE #contribution >0
Many thanks
I don't think that you need a variable here, also please confirm the "case when" syntax used. Here is a sample query:
select * from
(SElECT PMTS.VolunteerId ,SUM(CASE [Type]
WHEN 1003
THEN CASE WHEN PMTS.DateCreated BETWEEN #sd AND #ed
AND( PMTS.Amount >0 OR PMTS.Mileage >0)
AND PMTS.PaymentEventID = 0
THEN Amount END
ELSE 0 END) AS GPContributions
FROM PMTS)as A WHERE GPContributions >0
I have a query in MS SQL Server asking for name and some date-related information, depending on two dates, a start- and an enddate.
The problem is, I´m not always getting the same performance. Whenever I request something between the dates;
2010-07-01 00:00:00.000 and
2011-07-21 23:59:59.999
the performance is excellent. I get my result within mseconds. When I request something between these dates, for example,
2011-07-01 00:00:00.000 and
2011-07-21 23:59:59.999
the performance is.. less than good, taking between 20-28 seconds for each query. Do note how the dates giving good performance is more than a year between, while the latter is 20 days.
Is there any particular reason (maybe related to how DATETIME work) for this?
EDIT: The query,
SELECT ENAME,
SUM(CASE DATE WHEN 0 THEN 1 ELSE 0 END) AS U2,
SUM(CASE DATE WHEN 1 THEN 1 ELSE 0 END) AS B_2_4,
SUM(CASE DATE WHEN 2 THEN 1 ELSE 0 END) AS B_4_8,
SUM(CASE DATE WHEN 3 THEN 1 ELSE 0 END) AS B_8_16,
SUM(CASE DATE WHEN 4 THEN 1 ELSE 0 END) AS B_16_24,
SUM(CASE DATE WHEN 5 THEN 1 ELSE 0 END) AS B_24_48,
SUM(CASE DATE WHEN 6 THEN 1 ELSE 0 END) AS O_48,
SUM(CASE DATE WHEN 7 THEN 1 ELSE 0 END) AS status,
AVG(AVG) AS AVG,
SUM(DATE) AS TOTAL
FROM
(SELECT ENAME,
(CASE
WHEN status = 'Öppet' THEN 7
WHEN DATE < 48 THEN
(CASE WHEN DATE BETWEEN 0 AND 2 THEN 0
WHEN DATE BETWEEN 2 AND 4 THEN 1
WHEN DATE BETWEEN 4 AND 8 THEN 2
WHEN DATE BETWEEN 8 AND 16 THEN 3
WHEN DATE BETWEEN 16 AND 24 THEN 4
WHEN DATE BETWEEN 24 AND 48 THEN 5
ELSE - 1 END)
ELSE 6 END) AS DATE,
DATE AS AVG
FROM
(SELECT DATEDIFF(HOUR, cases.date, status.date) AS DATE,
extern.name AS ENAME,
status.status
FROM
cases INNER JOIN
status ON cases.id = status.caseid
AND status.date =
(SELECT MAX(date) AS Expr1
FROM status AS status_1
WHERE (caseid = cases.id)
GROUP BY caseid) INNER JOIN
extern ON cases.owner = extern.id
WHERE (cases.org = 'Expert')
AND (cases.date BETWEEN '2009-01-15 09:48:25.633'
AND '2011-07-21 09:48:25.633'))
AS derivedtbl_1)
AS derivedtbl_2
GROUP BY ENAME
ORDER BY ENAME
(parts of) The tables:
Extern
-ID (->cases.owner)
-name
Cases
-Owner (->Extern.id)
-id (->status.caseid)
-date (case created at this date)
Status
-caseid (->cases.id)
-Status
-Date (can be multiple, MAX(status.date) gives us date when
status was last changed)
I would have thought a statistics issue.
When you are only selecting the most recent dates these may be unrepresented in the statistics yet as the threshold has not yet been reached that would trigger auto updating.
See this blog post for an example.