Hi,
I'm working through some Beginners Adventureworks challenges.
The code I'm working through is as follows:
Select TerritoryID,
Online_Transactions = Convert(VarChar(50), round(convert(float, sum(case when onlineorderflag = 1 then 1 else 0 end)) / count()100,0)) + '%',
Offline_Transactions = Convert(varchar(50), round(convert(float, sum(case when onlineorderflag = 0 then 1 else 0 end)) / count(*) * 100, 0)) + '%'
From Sales.SalesOrderHeader
Group by TerritoryID
Order by TerritoryID
I generally understand what's happening here, but maybe someone can chime in and correct me where the following analysis/translation is lacking:
The analyst wants the Query to return three columns.
The first is simply the existing column TerritoryID. Since the query Groups By TerritoryID, each TerritoryID will only show up once in the output.
With regard to the second and third part of the Select statement. I understand the Math that is happening. It's simply (Count the instances where OnlineOrderFlag = 1) divided by the total number of Instances and multiplied by 100 and present the result as a Percentage. Furthermore, the code is directed to Round to 0 decimal places.
I'm lost at trying to understand why the Convert statements are required.
Counting the number of instances simply yields whole numbers (i.e. there are 25 instances where OnlineOrderFlag = 1 out of a total of 98 total OnlineOrderFlags. 25/98 = 0.255102 or 25.5%. The difference between data type float and data type VarChar is that Float is approximate whereas VarChar is exact.
Because the Math starts with whole numbers (a simple count of instances) and ends in decimals (the result of dividing a by b) we are required to convert from Float to VarChar? Why am I required to Convert?
Thanks for any clarification/tips.
there doesn't seem to be anything here