group inside sql code rather than in cfoutput - sql-server

I have a sql-server code of cities as rows and months as columns, there are sums by months but there are no sum by the city_id, I mean I have to count all the sum by city inside the output, and group it by city_id, anyway here is the sql code:
SELECT
SC.CITY_ID,SC.CITY_NAME, DATEPART(MM,I.INVOICE_DATE) AS INVOICE_MONTH,
JAN=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=1 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
FEB=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=2 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
MAR=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=3 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
APR=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=4 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
MAY=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=5 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
JUN=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=6 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
JUL=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=7 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
AUG=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=8 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
SEP=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=9 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
OCT=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=10 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
NOV=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=11 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
DEC=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=12 THEN COALESCE(NETTOTAL,0) ELSE 0 END)
FROM
SETUP_CITY SC
LEFT OUTER JOIN COMPANY C ON C.CITY = SC.CITY_ID
LEFT OUTER JOIN #DSN2_ALIAS#.INVOICE I ON I.COMPANY_ID = C.COMPANY_ID AND I.INVOICE_CAT IN (50,52,53,531,532,56,58,561,54,55,51,63,48) AND I.PURCHASE_SALES = 1
WHERE SC.COUNTRY_ID=1
GROUP BY SC.CITY_ID,SC.CITY_NAME,I.INVOICE_DATE
ORDER BY SC.CITY_ID,SC.CITY_NAME,I.INVOICE_DATE
and output:
<cfoutput query="get_top_sales_TOTAL" group="CITY_ID">
If I don't define the group by city_id, there are multiple rows of one city displayed. How is it possible to group the values (sum up) inside the sql code? So that I won't have to use the group statement inside the cfoutput?
Here is the screenshots to make it more clear, here's the screenshot with defined group="city_id"
If I don't define the group="city_id"

Mark is right about the invoice_month, there is no point for doing this. Your "correct" sql should be
SELECT
SC.CITY_ID,SC.CITY_NAME,
TOTAL=SUM(COALESCE(NETTOTAL,0)),
JAN=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=1 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
FEB=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=2 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
MAR=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=3 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
APR=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=4 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
MAY=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=5 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
JUN=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=6 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
JUL=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=7 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
AUG=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=8 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
SEP=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=9 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
OCT=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=10 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
NOV=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=11 THEN COALESCE(NETTOTAL,0) ELSE 0 END),
DEC=SUM(CASE WHEN DATEPART(MM,I.INVOICE_DATE)=12 THEN COALESCE(NETTOTAL,0) ELSE 0 END)
FROM
SETUP_CITY SC
LEFT OUTER JOIN COMPANY C ON C.CITY = SC.CITY_ID
LEFT OUTER JOIN #DSN2_ALIAS#.INVOICE I ON I.COMPANY_ID = C.COMPANY_ID
AND I.INVOICE_CAT IN (50,52,53,531,532,56,58,561,54,55,51,63,48)
AND I.PURCHASE_SALES = 1
WHERE SC.COUNTRY_ID=1
GROUP BY SC.CITY_ID, SC.CITY_NAME
ORDER BY SC.CITY_ID,SC.CITY_NAME

Your problem is that "invoice_date" in the group by and order by are going to produce multiple rows. Try this:
GROUP BY SC.CITY_ID, SC.CITY_NAME, DATEPART(MM,I.INVOICE_DATE)
ORDER BY SC.CITY_ID, SC.CITY_NAME, INVOICE_MONTH
Can't try it so I can't debug it - but basically your GROUP can't have individual items in it that expand the uniqueness of the row (as an "invoice date" would likely do). Good luck!

Related

Convert nvarchar to Int using Case When

Currently, i'm trying to convert '20190208-10h9m/1/1' to data type int. This string is identified under column String_Value. In addition, I'm pivoting using Case when syntax.
I've tried:
CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' TEHN PTXMEDE.STRING_VALUE ELSE 0 END), CAST(PTXMEDE.STRING_VALUE As nvarchar) As ID_TABLET
I get a converting error.
Full syntax below:
Select
PTXMEDE.ME,
(CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' THEN PTXMEDE.STRING_VALUE ELSE 0 END),CAST(PTXMEDE.STRING_VALUE As nvarchar) As ID_TABLET,
SUM(CASE WHEN PTXMEDE.PAT_ID = 'Q1_MD' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As Q1_MD,
SUM(CASE WHEN PTXMEDE.PAT_ID = 'Q1_FPROB' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As Q1_FPROB,
SUM(CASE WHEN PTXMEDE.PAT_ID = 'Q1_RESULT' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As Q1_RESULT,
SUM(CASE WHEN PTXMEDE.PAT_ID = 'WEIGHT' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As WEIGHT,
SUM(CASE WHEN PTXMEDE.PAT_ID = 'HARDNESS' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As HARDNESS,
MAX(CASE WHEN PTXMEDE.PAT_ID = 'WEIGHT.T2+' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As WEIGHTT2ULIMIT,
MAX(CASE WHEN PTXMEDE.PAT_ID = 'WEIGHT.T2-' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As WEIGHTT2LLIMIT,
MAX(CASE WHEN PTXMEDE.PAT_ID = 'HARDNESS.T2-' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As HARDNESST2LLIMIT,
MAX(CASE WHEN PTXMEDE.PAT_ID = 'CQA1Quality' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As CQA1Quality,
MAX(CASE WHEN PTXMEDE.PAT_ID = 'CQA2Quality' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As CQA2Quality,
MAX(CASE WHEN PTXMEDE.PAT_ID = 'CQA3Quality' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As CQA2Quality,
PTXMEDE.DATE_LOCAL,
PTXMEDE.SEQUENCE
FROM
PTXMEDE
JOIN PTXMIIF ON
PTXMIIF.ME = PTXMEDE.ME
WHERE
PTXMEDE.ME IN (
SELECT ME FROM PTXME
WHERE CX_STRING_4 = '20190210-6h31m'
AND MT = 'CDC_CU'
)
GROUP By PTXMEDE.ME, PTXMEDE.DATE_LOCAL,PTXMEDE.NUM_VALUE,PTXMEDE.SEQUENCE,PTXMEDE.STRING_VALUE, PTXMEDE.PAT_ID
My Expected result is to be able to list the value under STRING_VALUE Column
All branches of a CASE expression must have the same type in SQL. An "exception" to this would be where they don't have the same type, but the database does some implicit converting to right things (e.g. such as in MySQL). Here is a corrected version of your CASE expression:
CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' THEN PTXMEDE.STRING_VALUE ELSE '0' END
This would make the CASE expression output all text. If PTXMEDE.STRING_VALUE could be converted to an integer, then in theory you could also use this:
CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' THEN CAST(PTXMEDE.STRING_VALUE AS INT) ELSE 0 END
This would have the CASE expression return an integer value.

Using Case Statement to check multiple fields and return first matched true value

There are ten checkboxes on a form. When the form is completed I would like to know the result using a query in SSRS. The checboxes each have different names Checkbox1, Checkbox2, Checkbox3...with values of Yes when checked, and NULL uncheck. I want to calculate how many individual responses I received with one or more (multiple) checkboxes were checked off. How can I find out when multiple checkboxes are selected?
sum (case when Checkbox1='Yes' Or Checkbox2='Yes'
Or Checkbox3='Yes' Or Checkbox4='Yes' Or Checkbox5='Yes'
Or Checkbox6='Yes' Or Checkbox7='Yes' Or Checkbox8='Yes'
Or Checkbox9='Yes' Or Checkbox10='Yes' then 1 else 0 end) checkboxresult
If you convert the checkbox value to a numeric value of 1 or 0 then you can sum them to see if the total is more than one, e.g.
SELECT
ResponseID
,CASE
WHEN SUM(Checkbox1+Checkbox2+Checkbox3+Checkbox4+Checkbox5
+Checkbox6+Checkbox7+Checkbox8+Checkbox9+Checkbox10) > 1
THEN 'Multiple responses'
ELSE 'Zero or 1 responses'
END ResponseType
FROM
(
SELECT
ResponseID
,CASE Checkbox1 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox1
,CASE Checkbox2 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox2
,CASE Checkbox3 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox3
,CASE Checkbox4 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox4
,CASE Checkbox5 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox5
,CASE Checkbox6 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox6
,CASE Checkbox7 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox7
,CASE Checkbox8 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox8
,CASE Checkbox9 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox9
,CASE Checkbox10 WHEN 'Yes' THEN 1 ELSE 0 END AS Checkbox10
FROM
<SomeTable>
) Responses

Count data using SQL Server 2008

I'm using SQL Server 2008 and I have a big database, I need to count the data for every manzana but every rows is 0 so I don't know how to do that
SELECT
Manzana,
SUM(CASE WHEN Manzana IN( 'CBrc','CBrc1', 'CBrc2') THEN 1 ELSE 0 END )AS CBrc,
SUM(CASE WHEN Manzana IN ('W1','W11','W12','W13','W14','W15','W16') THEN 1 ELSE 0 END) AS W1,
SUM(CASE WHEN Manzana IN('PC1','PC11') THEN 1 ELSE 0 END) AS PC1,
SUM(CASE WHEN Manzana IN ('CLu','CLU1') THEN 1 ELSE 0 END) AS CLu,
SUM(CASE WHEN Manzana IN('S3','S31') THEN 1 ELSE 0 END) AS S3,
SUM(CASE WHEN Manzana IN ('C2L') THEN 1 ELSE 0 END) AS C2L,
SUM(CASE WHEN Manzana IN ('PCA') THEN 1 ELSE 0 END) AS PCA,
SUM(CASE WHEN Manzana IN ('ADO') THEN 1 ELSE 0 END) AS AD,
SUM(CASE WHEN Manzana IN ('PRC') THEN 1 ELSE 0 END) AS CBu,
SUM(CASE WHEN Manzana IN('SIN') THEN 1 ELSE 0 END) AS SIN_ACCESO_A_INFORMACION
FROM
dbo.Hoja3$
GROUP BY
Manzana
I need to obtain something like this
Manzana CBrc W1 PC1 CLU S3 C2L
5445 8 11 0 0 0 0
4545 15 0 30 0 0 0
5455 21 0 5 3 2 0
7893 0 0 3 1 0 0
1566 100 4 1 0 0 80
You can't group by Manzana and not group by Manzana. Also, from the sample data, I can tell that you haven't provided enough information. Just from the first row:
Manzana CBrc W1 PC1 CLU S3 C2L
5445 8 11 0 0 0 0
If Manzana is 5445, then what column has the value CBrc? It can't be the Manzana column, but has to be some other column. In this vacuum of information, I'm going to call the mystery column Code.
Then try this (of course, you'll need to put all your code groups in):
WITH CodeGroupings AS (
SELECT * FROM (VALUES -- Do this in a permanent table instead!
('CBrc%', 'CBrc'), -- can use wildcards
('W1_', 'W1'), -- or single letter wildcards
('PC1', 'PC1'), -- or just put individual values
('PC11', 'PC1'), -- mapping to the same group as the previous line
('SIN', 'SIN_ACCESO_A_INFORMACION')
) M (CodePattern, CodeGroup)
), ManzanaCodeGroups AS (
SELECT
H.Manzana,
CG.CodeGroup
FROM
dbo.Hoja3$ H
CROSS APPLY (
SELECT TOP 1 *
FROM CodeGroupings CG
WHERE H.Code LIKE CG.CodePattern
) CG
)
SELECT
*
FROM
ManzanaCodeGroups
PIVOT (Count(*) FOR (CodeGroup IN CBrc, W1, PC1, SIN_ACCESO_A_INFORMACION)) P
;
After reading your comment "I try to count how many Cbrc,Pc1, Clu etc I have in every Manzana" I see the problem.
You're using the IN operator incorrectly.
To test fo the occurrence of a substring use the CHARINDEX function:
SELECT
Manzana,
SUM( CASE WHEN CHARINDEX( 'SIN', Manzana ) > 0 THEN 1 ELSE 0 END ) AS SIN,
SUM( CASE WHEN CHARINDEX( 'PCA', Manzana ) > 0 THEN 1 ELSE 0 END ) AS PCA,
...
FROM
Hoja3$
GROUP BY
Manzana

How To Get Non-Null,Non-0 for Average with SqlServer Select

**Note: I need to go a little further and add NULLIF(0 or 5). I wrote a short post about my answer here:
http://peterkellner.net/2013/10/13/creating-a-compound-nullif-in-avg-function-with-sqlserver/
but am not happy with my solution)
I've got a table with results where attendees type in estimated attendance to a course. If they type 0 or leave it empty, I want ignore that and get the average of values typed in. I can't figure out how to add that constraint to my AVG function without having a where clause for the entire SQL. Is that possible? My code looks like this: (EstimatedNumberAttendees is what I'm going after).
SELECT dbo.SessionEvals.SessionId,
AVG(Cast (dbo.SessionEvals.CourseAsWhole as Float)) AS CourseAsWholeAvg,
COUNT(*),
COUNT(case
when dbo.SessionEvals.InstructorPromptness = 'On Time' then 1
else null
end) AS SpeakerOnTime,
COUNT(case
when dbo.SessionEvals.InstructorPromptness = 'Late' then 1
else null
end) AS SpeakerLate,
COUNT(case
when dbo.SessionEvals.InstructorPromptness = 'NoShow' then 1
else null
end) AS SpeakerNoShow,
COUNT(case
when dbo.SessionEvals.PercentFull = '10% to 90%' then 1
else null
end) AS PercentFull10to90,
COUNT(case
when dbo.SessionEvals.PercentFull = '> 90%' then 1
else null
end) AS PercentFullGreaterThan90,
COUNT(case
when dbo.SessionEvals.PercentFull = ' < 10% Full ' then 1
else null
end) AS PercentFullLessThan10,
AVG(Cast (dbo.SessionEvals.EstimatedNumberAttendees as Float)) AS
EstimatedAttending
FROM dbo.Sessions
INNER JOIN dbo.SessionEvals ON (dbo.Sessions.Id =
dbo.SessionEvals.SessionId)
WHERE dbo.Sessions.CodeCampYearId = 8
GROUP BY dbo.SessionEvals.SessionId
AVG omits NULLs. Therefore make it treat 0s as NULLs. Use NULLIF for that:
...
AVG(NULLIF(Cast (dbo.SessionEvals.CourseAsWhole as Float), 0)) AS CourseAsWholeAvg,
...
AVG(NULLIF(Cast (dbo.SessionEvals.EstimatedNumberAttendees as Float), 0)) AS EstimatedAttending
...
You can try to use an inner query to get the same sessions but exclude zero and null:
SELECT dbo.SessionEvals.SessionId,
(
SELECT AVG(SE1.CourseAsWhole)
FROM dbo.SessionEvals SE1
WHERE SE1.SessionId = dbo.SessionEvals.SessionId
AND ISNULL(SE1.CourseAsWhole, 0) <> 0
) AS CourseAsWholeAvg,
COUNT(*),
COUNT(case
when dbo.SessionEvals.InstructorPromptness = 'On Time' then 1
else null
end) AS SpeakerOnTime,
COUNT(case
when dbo.SessionEvals.InstructorPromptness = 'Late' then 1
else null
end) AS SpeakerLate,
COUNT(case
when dbo.SessionEvals.InstructorPromptness = 'NoShow' then 1
else null
end) AS SpeakerNoShow,
COUNT(case
when dbo.SessionEvals.PercentFull = '10% to 90%' then 1
else null
end) AS PercentFull10to90,
COUNT(case
when dbo.SessionEvals.PercentFull = '> 90%' then 1
else null
end) AS PercentFullGreaterThan90,
COUNT(case
when dbo.SessionEvals.PercentFull = ' < 10% Full ' then 1
else null
end) AS PercentFullLessThan10,
AVG(Cast (dbo.SessionEvals.EstimatedNumberAttendees as Float)) AS
EstimatedAttending
FROM dbo.Sessions
INNER JOIN dbo.SessionEvals ON (dbo.Sessions.Id =
dbo.SessionEvals.SessionId)
WHERE dbo.Sessions.CodeCampYearId = 8
GROUP BY dbo.SessionEvals.SessionId
SQL AVG function will by default ignore null values so you need to only exclude the 0s. Your AVG code can be changed to below:
AVG(nullif( Cast(dbo.SessionEvals.CourseAsWhole as Float), 0) AS CourseAsWholeAvg

SQL Server - need assistance with sum and case statements

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

Resources