CAST to Integer
Hi All,
I have a simple table(GL_Balance) as below: ( Columns: Account - Varchar(20), Dr -Decimal(15,2), Cr-Decimal(15,2))
Account
Dr Cr
2500
0.00 255.51
1400
255.51 0.00
3500
450.25 0.00
1420
0.00 450.25
I want to generate a result set, which should have, values appear as 0 in Dr and Cr columns when they have value of 0.00
I've done a query as below, but still I cannot get 0 in Dr and Cr columns when they are 0.00
select Account,
CASE WHEN Dr = 0.00 THEN CAST (Dr AS Int)
ELSE Dr
END as Dr
,CASE WHEN Cr = 0.00 THEN CAST (Cr AS Int)
ELSE Cr
END as Cr
From GL_Balance
It produce result as below:
Account
Dr Cr
2500
0.00 255.51
1400
255.51 0.00
3500
450.25 0.00
1420
0.00 450.25
But I want to have a result as Below:
Account
Dr Cr
2500
0 255.51
1400
255.51 0
3500
450.25 0
1420
0 450.25
Appreciate if some one can help .. Thanks .
Mira
Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. Why did you use a narrative that implies an awful design?
Your mindset is still stuck with Luca Pacioli and the days before negative numbers, so you cannot see that the traditional bookkeeping is a display issue, not a data modeling issue. Today, we use matrix methods and spreadsheets in accounting.
CREATE TABLE General_Ledger
(acct_nbr CHAR(20) NOT NULL PRIMARY KEY,
transaction_amt DECIMAL(15, 2) NOT NULL
CHECK (transaction_amt <> 0.00));
INSERT INTO General_Ledger
VALUES
('2500', -255.51),
('1400', 255.51),
('3500', 450.25),
('1420', -450.25);
>> I want to generate a result set, which should have, values appear as 0 in Dr and Cr columns when they have value of 0.00 <<
You might do this, but a database guy will not. We have a presentation layer that does this. Have you read a book on basic RDBMS and data modeling? You want to be writing a 1950's COBOL program. That language uses strings for numeric values; SQL does not.
If you want to do data splitting (an error in data modeling) you can play with this:
SELECT acct_nbr,
CASE SIGN (transaction_amt)
WHEN -1 THEN -transaction_amt
ELSE NULL END AS db,
CASE SIGN (transaction_amt)
WHEN +1 THEN transaction_amt
ELSE NULL END AS cr
FROM General_Ledger;
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Similar Messages
-
Parameter class casting problem
The question is: how to get the right method based on the type of the parameter passed?
Here is the code:
public class Test {
public static void main(String[] args) {
Integer l = 57; // automatic boxing
Object o = 43; // automatic boxing and widening casting (?)
print( l ); // OK: calls Integer
print( o ); // calls Object: not what I want, but could be
print( (Integer)o ); // OK: calls Integer
print( Integer.class.cast(o) ); // OK: calls Integer
print( o.getClass().cast(o) ); // NOT OK: dinamic casting does't work?
static void print( Integer l ) {
System.out.println("Integer: " + l.toString());
static void print( Object o ) {
System.out.println("Object: " + o.toString() + " (" + o.getClass().toString() + ")");
}Method overloads are resolved at compile time; meaning only the compile time type of the expression used as parameter is taken into account.
Class<T>.cast(Object)returns T.
Class<Integer>.cast returns Integer, so the first overload is chosen.
Class<Object>.cast returns Object, so here the second overload is chosen. -
Putting integer value of 163 into byte array
I have an integer value of 163. I need to put that into a byte array. When i do, it puts it as -93. Whats wrong? and how can i put it in correctly?
Hi,
You cannot store 163 in a byte variable. In Java a byte variable will have only 8 bits and its value range will be from -128 to +127. In a byte variable you cannot store a value which is out of this range. If you try to cast an integer value which is out of this range to byte then you will get unexpected results (But you can find what the result will be). -
Casting! what is it exactly?
can someone please explain to me in simple understandable words ( what is casting ) in Java?
Your help is highly appreciated.
ps( i read it in 3 differnt books, and it didnt make 100% full sense)
- when is it used?
- why?
- what does the code really mean when u caste things!
Thank youHi.
Ok, casting is the way to interpret an object in another available way.
Simple example:
double d = 1234.456;
int i;
i = (int)d;
d = (double) d; // or i = d;So, what does that mean:
After the cast, you interpret the double value from the point of an integer. When you print the integer, you would get the value 1234.
So when you cast the integer value back to the double, you have lost the fraction. For this cast you dont need to supply the castclass (the (double) or (int)).
So I have pointed out two ways of casting:
implizit casting (int to double, you dont loose value) and explizit casting (double to value, must be specified, cause value lost may happen). Whenever you have to make an explizit cast, you have to tell the compiler, how you want to cast.
Another example:
public class Car {
String name;
public Car(String name) {
this.name = name;
public String toString() {
return name;
public class BMW extends Car {
boolean cabrio;
public BMW(String name, boolean cabrio) {
super(name);
this.cabrio = cabrio;
public boolean isCabrio() {
return cabrio;
public doStuff() {
Car c = new Car("A car");
BMW bmw = new BMW("328i", true);
System.out.println("My first car: " + c); // print first car
System.out.println("My second car: " + bmw); // print second car
if (bmw.isCabrio())
System.out.println("Wow it's a cabrio!");
Car c2 = (Car) bmw; // how does the bmw look as a car?
bmw = (BMW) c; // this is an error!!!
}So. Now I have a class Car and a class BMW that is a subclass of car. When I cast BMW to Car I will loose the information, that my bmw was a cabrio. This happens because Car has no way to store the boolean information.
A Reason to do is, when I have a collection of items, and I know that they are all kinds of cars. But I dont know exactly (say they all are stored in a Vector), if the first car is a bmw or whatever. But I do know, they all are childs frm class Car (or whatever class framework you are working with).
Then I would cast the items of the Vector to my superclass Car and now do sth with it.
The next step to use casting is implementing Interfaces. And Interface just supplies some members or methods, that each class must override, when it uses that Interface.
So I cast my classes to that Interface. The reason I would do this, is, that I dont have to know the class type of that object, but I do know, that I can use all the methods or members supplied by the Interface. (You do have to check first if that cast is possible, but you can check this with the instanceof statement).
I hope I was a little help.
Christian -
Creating a dynamic Integer Array
Hi there.
This may seem trivial, but how do I create a dynamic array to store integers?
I tried Integer integerArray [] = new Integer (); but i get Cannot Resolve Symbol Error.
I am using Java 1.4.2 version.
Any suggestions would be helpful. ThanksDoesnt an ArrayList store values as
String? Even if i did use Integer.parseInt to cast to
Integer from String doesnt it become tricky if i have
to do much calculations?Hi,
An ArrrayList can store any object you wish not just String. All you need to specify when retrieving an object is the type of object you want.
For example, if you have an ArrayList of integers an you want to retrieve an integer from the list you would use:-
int myInt = (int)myArrayList.get(myIndex);Therefore if you want to store an arbitrary object foo in an ArrayList the code is thus:-
//replace foo with the object you are storing.
foo foobar = (foo)myArrayList.get(myIndex);There is a slight change with ArrayLists in Java 5 where you should declare the objects that should be stored in the list but hopefully the above helps you to understand that an ArrayList or any other Collection as it happens can store objects of your choosing.
Regards,
Chris -
Can someone tell me how to do this?
right now I have:
if (tempCourt==new Integer(courtNumber))tempCourt is an object of type Integer, and courtNumber is primitive int, cast as Integer ... however. this comparison isn't working.
where am I going wrong?
Thanks
SamWhat doesn't appear to work?
Both of the above solutions are perfectly alright and if you have a primitive at hand, go with the first one. No need to go for the object comparison. -
How to get rid of this unchecked cast warning?
Vector<Integer> v1 = new Vector<Integer>(); // ok
Object obj = (Object) v1; // ok
Vector<Integer> v2 = (Vector<Integer>) obj; //unchecked cast
It works when I try to cast Vector<Integer> to Object. However, it prompts "unchecked cast warning" when I try to cast the object back to Vector<Integer>. How can I get rid of this warning? Is there something wrong?There is nothing wrong (it is just a warning).
In the new type system, you would later do something like
Integer n = v2.get(14);Now the compiler cannot check (compile time maybe, run time never) whether obj is of class Vector<Integer> (Only Vector), as at compile time as type parameters are stripped away in java1.5 at run time ("type erasure").
So later the assignment to n could throw a class cast exception at run time. -
Explicit assignment of integer to a sString variable
how do I correctly cast this integer to the String variable?
where:
arrDspl[][] is String
arrCards is int
arrDspl[Glbl.r][Glbl.c] = (String) arrCards[Glbl.r][Glbl.c];You can't just cast; you have to convert.
To do this sort of thing, java provides objects and methods like the Integer object and its methods.
Here is an example conversion:
int i = 1;
String s = new (Integer(i).toString(); -
I was wondering if anyone knows whether it is possible to somehow apply method chaining on an object that requires a cast.
For example:
ArrayList ar = new ArrayList();
ar.add(new Integer(3));
int i = ar.get(0).intValue();The third line obviously produces a compile error to the effect that you can't call method intValue() on object Object.
To get the int value from the ArrayList above I have to do the following:
ArrayList ar = new ArrayList();
ar.add(new Integer(3));
Integer intObject = (Integer)ar.get(0);
int i = intObject.intValue();Is it at all possible to get the int value somehow without explicitly creating an Integer object? Is there a possible way to combine method chaining and casting in this case?You may combine the two lines by casting at the same time:
int i = ((Integer)ar.get(0)).intValue();
Notice the additional brackets to help the compiler understand the precedence of your intentions. It makes no sense if the compile tries to call intValue THEN cast to Integer.
When you call:
Integer intObject = (Integer)ar.get(0);
No Integer object is created, only a reference to the object is created. I'm not sure if an implicit reference is created in the previous example, but I see no substantial benefit using the first method. In fact I won't use it as its not very readable (to me). -
i have a problem. i want to return a double value by the division of two integers. the values i am getting is not as expected. for example if the lectureduration =3,and no_of_session =2, i expect to get 1.5 but i am getting 1.0.
here are some of the codes.
double calculate()
double i;
System.out.println(lectureduration+"\t"+no_of_session);
i=(float)(lectureduration/no_of_session);
return i;
public static void main(String args[])
prof p= new prof();
p.setsession(2);
p.setlectureduration(3);
double a=p.calculate();
System.out.println(a);
p.setsession(1);
p.setlectureduration(3);
a=p.calculate();
System.out.println(a);
can anyone help??
thank you.You need to understand that integer division results in an integer value. You cast to float casts the integer result toa float.
-
Hi:
What is meant when a parameter or a cast etc. is referred as implicit?
What is meant when a parameter or a cast etc. is referred as explicit?
Thanks.implicit: Implied or understood though not directly expressed.
For instance:
Integer i = new Integer(42);
Object obj = i; // Implicit cast from Integer to Object
explicit: Fully and clearly expressed; leaving nothing implied.
For instance:
Object obj = new Integer(42);
Integer i = (Integer)obj; // Explicit cast from Object to Integer -
How can I use multiple constructor
Hi,
I have some problem to using multiple constructor in java. It shows some error while compiling the following program. can any one give better solution for me.......
public class Test6{
public Test6(){
this(4); /*
C:\Test6.java:5: cannot find symbol
symbol : constructor Test6(int)
location: class Test6
this(4);
Test6(byte var){
System.out.println(var);
public static void main(String[] args){
Test6 t6 = new Test6();
}A number like 4 is an integer literal. So, you are passing an int to a function that is defined to accept a byte, hence you have a type mismatch. You need to cast the integer literal to a byte before passing it to the function:
this( (byte) 4); -
Reading in a text file to GUI for later analysis
Good Morning any and everyone,
I'm trying to get a piece of code working to read in a text file and it isn't working very well. The code has been seriously crunched together from a multitude of sources so I suspect that the error has occurred from there.
The errors that are occurring are "Can't Find Symbol" errors. Only 2 of them though which is a lot less than I had earlier. Now I'm just banging my head against the wall.
Has anyone got any suggestions as to where I'm going wrong? Anything greatly appreciated.
(PS> Please be gentle, I'm still a newbie)
Thanks.
import java.util.*; // required for List and ArrayList
import java.io.*; // required for handling and IOExceptions
import javax.swing.*;
public class textAnalyser extends JFrame // implements ActionListener
// the attributes
// declare a TextArea
private JTextArea viewArea = new JTextArea(10,55);
// declare the menu components
private JMenuBar bar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenu quitMenu = new JMenu("Quit");
private JMenuItem selectChoice = new JMenuItem("Select");
private JMenuItem runChoice = new JMenuItem("Run");
private JMenuItem reallyQuitChoice = new JMenuItem("Really quit");
private JMenuItem cancelChoice = new JMenuItem("Cancel");
// declare an attribute to hold the chosen file
private File chosenFile;
// the constructor
public textAnalyser()
setTitle("Text Analyser"); // set title of the frame
add(viewArea); // add the text area
// add the menus to the menu bar
bar.add(fileMenu);
bar.add(quitMenu);
// add the menu items to the menus
fileMenu.add(selectChoice);
fileMenu.add(runChoice);
quitMenu.add(reallyQuitChoice);
quitMenu.add(cancelChoice);
// add the menu bar to the frame
setJMenuBar(bar);
// add the ActionListeners
// selectChoice.addActionListener(this);
// runChoice.addActionListener(this);
// reallyQuitChoice.addActionListener(this);
// cancelChoice.addActionListener(this);
// configure the frame
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setSize(450,200);
setVisible(true);
public void actionPerformed(ActionEvent e)
if(e.getSource() == displayContentsChoice)
try
final int MAX = 300;
FileReader textFile = new FileReader("textfile.txt");
BufferedReader textStream = new BufferedReader(textFile);
int ch; // holds integer value of character
char c; // holds character when type cast from integer
int counter = 0; //counts number of characters read
ch = textStream.read(); //reads the first character from the file
c = (char) ch; //type cast from integer to character
viewArea.append("\n");
/* continue through the file until either the end of the file or the maximum
number of characters allowed have been read*/
while(ch != -1 && counter <= MAX)
counter++; // increment the counter
viewArea.append("" + c); // display the character
ch = textStream.read(); // read the next character
c = (char) ch;
textStream.close();
viewArea.append("\n");
catch(IOException ioe)
if(chosenFile == null) // no file selected
viewArea.append("No file selected\n");
else
viewArea.append("There was a problem reading the file\n");
}A couple of points:
*You've commented out stuff that is needed, like the adding of actionlisteners, the implements actionlistener,...
*Your actionlistener is looking for a menu choice which doesn't exist "displayContentsChoice". Does this menu item need to be created?
*How much of this code have you yourself created? Do you understand its inner working?
*What is the purpose of this code? Is it for work? School? Homework?
Good luck!
/Pete -
I'm getting a compiler warning with generics in J2SDK1.5.0
javac -source 1.5 -target 1.5 -Xlint:unchecked Test.java
Test.java:72: warning: unchecked cast to type TYPE mValues = (TYPE[])new Object[aInitialSize];
My code is below, and ideas why this warning appears, is it a bug in my code or is the compiler faulty?
(crosspost warning, I posted the same question on www.javalobby.org, no need for flaming...)
static class Array
private TYPE [] mValues;
public Array(int aInitialSize)
mValues = (TYPE[])new Object[aInitialSize];
public void set(int aIndex, TYPE aValue)
mValues[aIndex] = aValue;
public TYPE get(int aIndex)
return mValues[aIndex];
Sincerely,
Patrik OlssonI asked Sun about this and they replayed:
No, because it is not typesafe. Consider the code
class A<T> {
T[] f() { return (T[])new Object[10]; }
This will cause a class cast exception in its caller, even if the caller has no
cast:
A<Integer> ai = new A<Integer>();
Integer[] a = ai.f(); // BOOM!
Don't use arrays. Use collections. -
Grand Total function on a report
The Grand Total function is working for only one of the two columns I need it to work in for my report. The data in the column in question is text data that has been CASTed to Integer with no issues but still won't display a grand total. Exporting to Excel works fine for both column totals but that defeats the purpose and is mentioned as a possible troubleshooting clue.
Check over <a href = "http://forums.oracle.com/forums/thread.jspa?threadID=951997&tstart=0" target = "_blank">here</a>
Regards
Maybe you are looking for
-
Got a new harddrive in my 2010 macbook pro and rebooted it with time machine back up from a older mac running 10.5.8. I loaded snow leopard 10.6 from disc then updated to 10.6.8 on new computer after restore from back up. Now the Safari icon, syste
-
Displayport L420- DELL monitor
Dear, I have a L420 and connect it to a Dell U2711 monitor- the monitor itself function as hub for mouse, keyboard etc-. The Dell monitor is connected to my laptop through display port andUSB. For practical reasons I would like to put my computer at
-
What is the best way to get a tune created in GB for iPad into iMovie for iPad?
What is the best way to get a tune created in GB for iPad into iMovie for iPad?
-
Distribute by Reference Data from Sender to Recipient planning function?
Hi all; Im trying to use the planning function Distribute by Reference Data from Sender to Recipient to distribute the reference data by material to plan data. This is: Reference Data: Version: 001 0vtype: 010 Material: M1; M2; M3 Sub-brand: SB1;
-
Asked to insert my password, from a keychain I don't have?
I'm trying to log in to my Microsoft Lync account, but I get a notification asking for my password from a keychain I don't have. So how am I suppose to know the password? The problem is that I can't even find that specific keychain (or Lync in my key