Dividing sum of varchar fields?
I'm using SQL Server 2014 and I have the following table containing two varchar fields I need to sum and divide:
CREATE TABLE.[VMs](
[VMID] [int] IDENTITY(1,1) NOT NULL,
[vCenter] [varchar](100) NULL,
[VMName] [varchar](100) NULL,
[Template] [varchar](100) NULL,
[PowerState] [varchar](100) NULL,
[ClusterName] [varchar](100) NULL,
[Disk] [int] NULL,
[DiskPartition] [varchar](70) NULL,
[DiskSizeGB] [decimal](10, 3) NULL,
[Hostname] [varchar](100) NULL,
CONSTRAINT [PK_VMs] PRIMARY KEY CLUSTERED
[VMID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
I'm trying to get the distinct sum of 'VMName' and 'Hostname' to get the count of each, and then divide the 'VMName' count by 'Hostname' count on a per 'vCenter' basis.
I'm not sure how to perform calculations against the varchar fields and any help would be appreciated.
Thanks in advance
Adam
This is the main query, the top portion was sample data I just put based on your provided data
;With CTE
AS
SELECT
vCenter
,COUNT(DISTINCT VMName) As CountVMName
,COUNT(DISTINCT HostName) As CountHostName
FROM
@myTable
GROUP BY
vCenter
SELECT *, (CASE WHEN CountHostName <> 0 THEN CountVMName / CountHostName ELSE 0 END) As CountPerVCenter
FROM
CTE
Best Wishes, Arbi; Please vote if you find this posting was helpful or Mark it as answered.
Similar Messages
-
Just noticed it isn't straight forward to SUM a DATETIME fields.
I’ve used the following code to get the time, how do I convert the output back to a DATETIME field?
declare @T table
total_hours_worked datetime
insert into @T values ('01:00:00')
insert into @T values ('01:30:00')
insert into @T values ('03:35:00')
select *
from @T
select SUM((DATEPART(hh,total_hours_worked)*60)+DATEPART(mi,total_hours_worked)+(DATEPART(ss,total_hours_worked)/(60.0)))/60.0 as TotalHours from @T
Thanks,I should have added the disclaimer that my solution would require total_hours_worked to be stored as either a float or a varchar to be used with the function I described above. The completed functions would be similar to
CREATE FUNCTION dbo.TimeSpan_CreateFromString
@pFormattedTimeSpan varchar(128) = null
RETURNS float(53)
with returns null on null input AS
BEGIN
declare @DayPortion int
,@HourPortion int
,@MinutePortion int
,@SecondPortion decimal(6,4)
declare @l int
declare @s2 varchar(128)
DECLARE @Result float(53)
select @s2=LTRIM(rtrim(@pFormattedTimeSpan))
set @l = LEN(@s2)
declare @i int
if CHARINDEX('.',@s2,1) < CHARINDEX(':',@s2,1)
begin
set @i = CHARINDEX('.',@s2,1)
select @DayPortion =
case CHARINDEX('.',@s2)
when 0 then 0
else
case ISNUMERIC(SUBSTRING(@s2,1,CHARINDEX('.',@s2)-1))
when 1 then CAST(SUBSTRING(@s2,1,CHARINDEX('.',@s2)-1) as int)
else 0
end
end;
set @s2=ltrim(rtrim(SUBSTRING(@s2,@i+1,@l-(@i))))
end
else
begin
set @DayPortion=0
end
-- ** debug: select @i, @l, @s2
--select CHARINDEX(':',@s2,1) [c1], CHARINDEX(':',@s2,CHARINDEX(':',@s2,1)+1) [c2], CHARINDEX(':',@s2,(CHARINDEX(':',@s2,CHARINDEX(':',@s2,1)+1))+1) [c3]
set @i = CHARINDEX(':',@s2,1)
select @HourPortion =
case CHARINDEX(':',@s2,1)
when 0 then 0
else
case ISNUMERIC(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1))
when 1 then CAST(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1) AS int)
else null
end
end
set @s2=ltrim(rtrim(SUBSTRING(@s2,@i+1,@l-(@i))))
-- ** debug: select @i, @l, @s2
set @i = CHARINDEX(':',@s2,1)
select @MinutePortion =
case CHARINDEX(':',@s2,1)
when 0 then 0
else
case ISNUMERIC(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1))
when 1 then CAST(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1) AS int)
else null
end
end
set @s2=ltrim(rtrim(SUBSTRING(@s2,@i+1,@l-(@i))))
-- ** debug: select @i, @l, @s2
set @i = CHARINDEX(':',@s2,1)
select @SecondPortion =
case ISNUMERIC(@s2)
when 0 then null
else CAST(@s2 as decimal(6,4))
end
SELECT @Result = dbo.TimeSpan_CreateFromParts(@DayPortion,@HourPortion,@MinutePortion,@SecondPortion);
RETURN @Result
END
GO
I changed the function names to make them more consistent. -
Hello Guys,
I'm using 'REUSE_ALV_GRID_DISPLAY' in my prog.
There is a field in output table which is of type P(8) Decimals 3.
When I'm trying to get the sum of this field in ALV Display it gives the message " Desired operation cannot be performed for column 'Converted Quantity' ".
I have also tried do_sum = 'X'.
But it is not working. Please help guys.
Regards,
AbhinavThanks a lot guys for your inputs.
The program is working now.
Now I'm using :
CLEAR wa_fieldcat.
wa_fieldcat-fieldname = 'QUAN'.
* wa_fieldcat-ref_tabname = 'I_OUT2'.
* wa_fieldcat-tabname = 'I_OUT2'.
wa_fieldcat-qfieldname = 'MEAS'.
wa_fieldcat-qtabname = 'I_OUT2'.
wa_fieldcat-outputlen = '15'.
wa_fieldcat-seltext_l = text-052.
APPEND wa_fieldcat TO i_fieldcat.
The program is working fine now.
I have commented tabname and -ref_tabname , and the program is working fine now.
Thanks a lot. -
Dump when summing up CURR field in ALV GRID display
Hi All,
I am getting dump when I try to sum the CURR field in my ALV Grid Display. The field is of CURR 23. I am using classes and methods to display alv grid.
I tried passing <fs_fieldcat>-do_sum = 'X'. When I did this, it is dumping without even displaying the alv grid.
Here is the part it is throwing dump:
ls_lvc_data-value = space.
clear ls_lvc_data-style.
loop at it_fcat_local assigning <ls_fcat>
where tech ne 'X' and no_out ne 'X'.
if l_invisible eq 'X'.
clear l_invisible.
if <ls_fcat>-do_sum is initial.
continue.
else.
clear ls_lvc_data-col_pos.
endif.
endif.
add 1 to ls_lvc_data-col_pos.
assign component <ls_fcat>-fieldname
of structure <ls_data> to <l_field_value>.
_if sy-subrc ne 0.
message x000(0k).
endif._
Regards,
GuruThomas,
Here is the dump:
Runtime Errors MESSAGE_TYPE_X
Date and Time 10/22/2010 23:30:53
Short text
The current application triggered a termination with a short dump.
What happened?
The current application program detected a situation which really
should not occur. Therefore, a termination with a short dump was
triggered on purpose by the key word MESSAGE (type X).
Error analysis
Short text of error message:
Long text of error message:
Technical information about the message:
Message class....... "0K"
Number.............. 000
Variable 1.......... " "
Variable 2.......... " "
Variable 3.......... " "
Variable 4.......... " "
How to correct the error
Probably the only way to eliminate the error is to correct the program.
If the error occures in a non-modified SAP program, you may be able to
find an interim solution in an SAP Note.
If you have access to SAP Notes, carry out a search with the following
keywords:
"MESSAGE_TYPE_X" " "
"SAPLSLVC" or "LSLVCF36"
"FILL_DATA_TABLE"
If you cannot solve the problem yourself and want to send an error
notification to SAP, include the following information:
1. The description of the current problem (short dump)
To save the description, choose "System->List->Save->Local File
(Unconverted)".
2. Corresponding system log
Display the system log by calling transaction SM21.
Restrict the time interval to 10 minutes before and five minutes
after the short dump. Then choose "System->List->Save->Local File
(Unconverted)".
3. If the problem occurs in a problem of your own or a modified SAP
program: The source code of the program
In the editor, choose "Utilities->More
Utilities->Upload/Download->Download".
4. Details about the conditions under which the error occurred or which
actions and input led to the error.
Source Code Extract
Line
SourceCde
2708
is_subtottxt_info = ls_subtot_info
2709
ip_subtot_line = lr_data
2710
changing
2711
c_subtottxt = l_subtottxt.
2712
ls_lvc_data-value = l_subtottxt.
2713
2714
append ls_lvc_data to ct_lvc_data.
2715
endif.
2716
2717
2718
Column per Fieldcat Entry
2719
2720
ls_lvc_data-value = space.
2721
clear ls_lvc_data-style.
2722
loop at it_fcat_local assigning <ls_fcat>
2723
where tech ne 'X' and no_out ne 'X'.
2724
if l_invisible eq 'X'.
2725
clear l_invisible.
2726
if <ls_fcat>-do_sum is initial.
2727
continue.
2728
else.
2729
clear ls_lvc_data-col_pos.
2730
endif.
2731
endif.
2732
2733
add 1 to ls_lvc_data-col_pos.
2734
2735
assign component <ls_fcat>-fieldname
2736
of structure <ls_data> to <l_field_value>.
2737
if sy-subrc ne 0.
>>>>>
message x000(0k).
2739
endif.
2740
2741
*... work on average
2742
if <ls_fcat>-do_sum eq 'C'.
2743
Initialize average result and entries
2744
<l_field_value> = 0.
2745
clear l_entries.
2746
2747
retrive unit from fieldcatalog
2748
assign space to <l_unit>.
2749
if not <ls_fcat>-cfieldname is initial.
2750
assign component <ls_fcat>-cfieldname
2751
of structure <ls_data> to <l_unit>.
2752
endif.
2753
if not <ls_fcat>-qfieldname is initial.
2754
assign component <ls_fcat>-qfieldname
2755
of structure <ls_data> to <l_unit>.
2756
endif.
2757 -
Hello Guys,
CAn any one tell me how to do the SUM for a particular column in ALV.It should display at the End of the records.The column field is TYPE N(4).
My CODE is like this:
CLEAR fc_tmp.
fc_tmp-col_pos = 5.
fc_tmp-reptext_ddic = 'POINTS'.
fc_tmp-fieldname = 'POINTS'.
fc_tmp-tabname = 'ITAB'.
fc_tmp-outputlen = 15.
fc_tmp-key = 'X'.
fc_tmp-do_sum = 'X'.
APPEND fc_tmp TO fieldcat.
This is not working.
Thanks in Advance,
Take careHi,
populate the IT_SORT internal table of REUSE_ALV_GRID_DISPLAY provided in the importing parameters.
fieldname = Company Code
append fieldname to it_sort.
fieldname = division.
append fieldname to it_sort.
If you explicitly need subtotals then add the following line
subtot = 'X'
For obtaining sum you have an attribute "do_sum" in fieldcatalog , set it to 'X' and you should be able to do sum on that field.
<b>Ensure that these should be numeric / currency or quantity datatypes only.</b>
wa_fieldcat-datatype = 'CURR'. or
wa_fieldcat-datatype = 'QUAN'.
Hope this solves your problem
Cheers,
Simha.
PS : Please reward points if solution is helpful -
Material description filled automatically as the sum of two fields
Hello to all
We can automate the process of the creation a new material doing that the field material description(MAKT-MAKTX) can be filled by the system before saving(not by the user) as the sum of two fields in the MARA table that the users will be filled manually.
Is it possible using a user exit, field exit,....?
Thanks in advance.
RegardsHello to all
We can automate the process of the creation a new material doing that the field material description(MAKT-MAKTX) can be filled by the system before saving(not by the user) as the sum of two fields in the MARA table that the users will be filled manually.
Is it possible using a user exit, field exit,....?
Thanks in advance.
Regards -
[CR integrated in VS 2005] - sum of string fields
Hello,
i am discovering CR,
and i am trying to do the sum of a field (number) but declared as string. the declaration of the field cannot be changed (string in the database).
so i want to do the sum of this field.
i wonder if it is possible, and if yes, how.
maybe something like a formula.
I saw the functions: ToNumber () and Cdbl() for conversion, and Sum().
If someone has an idea, i will be very interested.
PS: sorry if my question is not understandable, i'm french. If you don't understand it, i would rewrite it.
thank you!thank you.
I could convert, but the problem is to make the sum of the conversion.
i would like to do something like:
Sum(ToNumber ()) but CR does not accept it.
Maybe by using a variable in a formula (but i don't know where):
shared numbervar total;
total = total+ToNumber({MyField});
and when printing a formula field at the bottom of the report to show the total:
shared numbervar total;
ToText (total); -
Best practice to define length for varchar field of table in sql server
What is best practice to define length for a varchar field in table
where field suppose Remarks By Person varchar(max) or varchar(4000)
Could it affect on optimization in future????
experts Reply Must ...
Dilip Patil..Hi Dilip,
Varchar(n/max) is a variable-length, non-unicode character data. N defines the string length and can be a value from 1 through 8,000. Max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size is the actual length of the data entered
+ 2 bytes. We always use varchar when the sizes of the column data entries vary considerably. While if the filed data size might exceed 8,000 bytes in some way, we should use varchar(max).
So the conclusion is just like Uri said, use varchar(max) or varchar(4000) is depends on how much characters we are going to store.
The following document about varchar in SQL Server is for your reference:
http://technet.microsoft.com/en-us/library/ms176089.aspx
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support -
I have a procedure which accepts a varchar field as input and compares it with each value in a table. how do I code it.
e.g. proc1(xx IN varchar, yy OUT)
--say column name is abc then
where abc = xx;
Dosent giving any output.here it goes
SQL> ED
Wrote file afiedt.buf
1 CREATE OR REPLACE PROCEDURE
2 COMPARE_VARCHAR_FIELDS(XX IN VARCHAR,YY OUT VARCHAR)
3 IS
4 A NUMBER:=0;
5 BEGIN
6 FOR I IN (SELECT * FROM AX WHERE X=XX)
7 LOOP
8 A:=A+1;
9 END LOOP;
10 IF A>0 THEN
11 YY:=XX||' FOUND '||A||' TIMES';
12 ELSE
13 YY:=XX||' NOT FOUND';
14 END IF;
15* END;
SQL> /
PL/SQL procedure successfully completed.
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 Z VARCHAR2(40);
3 BEGIN
4 COMPARE_VARCHAR_FIELDS('x',z);
5 dbms_output.put_line(z);
6* end ;
SQL> /
PL/SQL procedure successfully completed.
SQL> set serveroutput on
SQL> /
x FOUND 3 TIMES
PL/SQL procedure successfully completed. -
It's been a day of learning. I found out that when Kodo gets a
columnlength of -1 for a String field, it will ask the Dictionary for
the sql for generating a Clob. Also when Kodo finds a positive
columnlength it will call getLenString on the dictionary.
We're using MySQL and in this case, when the column-length of a String
is set to -1 this creates a TEXT field and when the column-length is
positive this creates a VARCHAR(column-length) field.
When querying the database, Kodo once again turns to the meta data. When
the column-length has been set to -1 Kodo does a separate query for each
text field. If the column-length is positive, Kodo includes the field in
it's default-fetch-group.
Am I correct so far?
The problem I have is that when a query for a certain field is
performed, I want it to be in the first group fetched. It is always
needed and not that large at all. It will at most be 1500 characters. In
SQL Server and possibly others, I can put the column-length at 1500 and
wind up with a varchar field of 1500 characters long. MySQL however,
does not support anything over 255 characters for a varchar field.
So, I need to create a field of type TEXT to allow it to contain more
than 255 chars. However, I do not want a separate query for the field
since it won't be that big anyway.
I've been able to get this working using the column-length -1 at schema
time and the value 1500 at runtime. This is not at all convenient and
will very likely result in a wrong schema being created or the wrong
query being run in the long run.
Is the solution I just mentioned the only one, or are there other scenarios?
Thanks in advance,
Martin van DijkenMartin-
Your analysis is exactly right. Kodo 3.0 allows a lot more latitude in
how this behavior is defined.
One way in which you might be able to get around this problem is to
leave the "column-length" attribute to -1, but manually force the
mapping to not be the ClobMapping (which is the mechanism by which Kodo
knows to issue a separate query for the object). You can do this by
setting the "custom-mapping" field-level metadata extension to
"com.solarmetric.kodo.impl.jdbc.ormapping.ValueMapping".
I'll be interested to know if this works for you.
In article <[email protected]>, Martin van Dijken wrote:
It's been a day of learning. I found out that when Kodo gets a
columnlength of -1 for a String field, it will ask the Dictionary for
the sql for generating a Clob. Also when Kodo finds a positive
columnlength it will call getLenString on the dictionary.
We're using MySQL and in this case, when the column-length of a String
is set to -1 this creates a TEXT field and when the column-length is
positive this creates a VARCHAR(column-length) field.
When querying the database, Kodo once again turns to the meta data. When
the column-length has been set to -1 Kodo does a separate query for each
text field. If the column-length is positive, Kodo includes the field in
it's default-fetch-group.
Am I correct so far?
The problem I have is that when a query for a certain field is
performed, I want it to be in the first group fetched. It is always
needed and not that large at all. It will at most be 1500 characters. In
SQL Server and possibly others, I can put the column-length at 1500 and
wind up with a varchar field of 1500 characters long. MySQL however,
does not support anything over 255 characters for a varchar field.
So, I need to create a field of type TEXT to allow it to contain more
than 255 chars. However, I do not want a separate query for the field
since it won't be that big anyway.
I've been able to get this working using the column-length -1 at schema
time and the value 1500 at runtime. This is not at all convenient and
will very likely result in a wrong schema being created or the wrong
query being run in the long run.
Is the solution I just mentioned the only one, or are there other scenarios?
Thanks in advance,
Martin van Dijken
Marc Prud'hommeaux [email protected]
SolarMetric Inc. http://www.solarmetric.com -
Converting varchar field to date
I got a varchar field in DB with format YYYY/MM/DD HH:MI:SS in DB . I want to convert this to date field in RPD. When I did
CAST ( VarChar field AS DATE) in RPD it is not working I am getting sql error.
Thanks for your help.Hi,
can you try once to cast your char as a timestamp.
Hope that works.
Kr,
A -
How to calculate sum of the fields in adobeforms
Hello Experts
can i know how to calculate sum of fields in the adobe form. I have few fields to be summed in total field.
RegardsHello Surendra,
Suppose you are having 4 fields and the 4th field is the TOTAL field.
Write the below Javascript on the Initialize event of TOTAL field as shown below.
Remember that if you use just "+" sign without Number() or ParseInt() function it acts like String Concatenation.
this.rawvalue = Number( this.parent.field1.rawvalue ) +
Number( this.parent.field2.rawvalue ) +
Number( this.parent.field3.rawvalue ) ;
You can also write is as shown below.
this.rawvalue = parseInt( this.parent.field1.rawvalue ) +
parseInt( this.parent.field2.rawvalue ) +
parseInt( this.parent.field3.rawvalue ) ; -
Automatically trim a varchar field in an update SQL
We have an ETL application that does an update with a varchar field. When the field contains spaces, we see that with an update these spaces are trimmed automatically. We wonder whether there is a HANA setting that can be set to disable this trim....
For your ETL, Is HANA the source system?
If yes, then you got to change at ETL side right?
Regards,
Krishna Tangudu -
Using a varchar field as number on ui
Hello
In one of the requirements we got to use a varchar field in db to store as number in UI. The user may specify + or - in the begining and it can be number up to 2 decimal places.
So, how to achieve this?
We are using jdev 11.1.1.6.2may be have a transient field with number datatype and use af:convertNumber with minFractionDigits and maxFractionDigits to 2. it would take - not sure about + sign (might remove automatically). convert this as string and try saving it with your actual field.
-
Getting all VARCHAR fields with string length different then x
Hello,
I am trying to get from a table all the rows which contain in a certain varchar field a string length different than x (5 i.e.):
varchar field
treds
fd <-
grgrt
sdfsdfsdf <-
fdsds
the marked rows will been given out.
Thanks!Term, the Oracle SQL manual contains documentation on the Oracle functions. Most of the functions can be classified as either character functions, number (math) functions, date functions, and conversion functions.
If you are going to work with Oracle you will benefit from looking on the list of available functions to become familiar with what is available.
HTH -- Mark D Powell --
Maybe you are looking for
-
Getting Runtime Error while Activating Characteristics in BW sandbox system
Hi, i m getting runtime error while activating Characteristics. Error as All InfoObjects Already Saved(locked) Short Text SQL error 1691 occurred when accessing program "GP4H8Z73D1WOGH7XBIZ54N5GXEG " Runtime Errors DBIF_REPO_SQL_ERROR eve
-
Illustrator/InDesign problems with AFP shares on Xsan
Hi, Has anyone else been having problems with Adobe apps overwriting files on AFP shares that are stored on an Xsan? Errors that come up vary from error -47 to error -5000 and generally mention that the user doesn't have permission. They do have perm
-
Strange colored squares on display, Yosemite
Since I upgraded to Yosemite I have a serous problem with my display. After a while the computer freezes completely and I have to restart (hard) Mac Pro (Early 2009) 2 x 2.26 GHz Quad-Core Intel Xeon 24 GB 1066 MHz DDR3 ECC ATI Radeon HD 5870 1024 MB
-
Anybody tried this one yet? http://catalog2.panasonic.com/webapp/wcs/stores/servlet/ModelDetail?displayTab=O &storeId=11201&catalogId=13051&itemId=406091&catGroupId=34402&surfModel=AJ-PCD2G PJ Currently using the DuelAdapter, but wouldn't mind someth
-
How to protect the media file ...?
hi i want to protect my media file i used binaryio xtra its works but problem is that when i run the director project exe file then during execution the media file decoce and user can run the media file on any media player tell me what i do? plz tell