Decode
Hello,
Below is a query To note number of employees hired by year...If I want the format to look like
No of employees (Total) Hired in 1996 Hired in 1997 Hired in 1998 Hired in 1999
XXX 10 28 23 18
What is the best approach if I was to use Decode function?
SQL>select to_char(hire_date,'YYYY') "Hire-Date",count(*) "Number of Employees"
from employees
group by to_char(hire_date,'YYYY')
having to_char(hire_date,'YYYY') in (1996,1997,1998,1999)
Hire-Date Number of Employees
1997 28
1999 18
1996 10
1998 23
user8479432 wrote:
Hello,
Below is a query To note number of employees hired by year...If I want the format to look like
No of employees (Total) Hired in 1996 Hired in 1997 Hired in 1998 Hired in 1999
XXX 10 28 23 18
What is the best approach if I was to use Decode function? The generic term for that is Pivot . The FAQ of this forum has several good links:
SQL and PL/SQL FAQ
If you're using Oracle 10 (or earlier) then CASE (or DECOCDE, ir you prefer it) is the best way. Starting in Oracle 11.1, use SELECT ... PIVOT instead.
SQL>select to_char(hire_date,'YYYY') "Hire-Date",count(*) "Number of Employees"
from employees
group by to_char(hire_date,'YYYY')
having to_char(hire_date,'YYYY') in (1996,1997,1998,1999)
/Not that you asked, but if you have a choice of filtering in the WHERE clause or the HAVING clause, the WHERE clause will always be more efficient. It would probably be a lot faster if you said something like
WHERE hire_date >= DATE '1996-01-01'
AND hire_date < DATE '2000-01-01'especailly if you have an index on hire_date.
Similar Messages
-
Logical Operations in SQL decode function ?
Hi,
Is it possible to do Logical Operations in SQL decode function
like
'>'
'<'
'>='
'<='
'<>'
not in
in
not null
is null
eg...
select col1 ,order_by,decode ( col1 , > 10 , 0 , 1)
from tab;
select col1 ,order_by,decode ( col1 , <> 10 , 0 , 1)
from tab;
select col1 ,order_by,decode ( col1 , not in (10,11,12) , 0 , 1)
from tab;
select col1 ,order_by,decode ( col1 ,is null , 0 , 1)
from tab;
Regards,
infan
Edited by: user780731 on Apr 30, 2009 12:07 AM
Edited by: user780731 on Apr 30, 2009 12:07 AM
Edited by: user780731 on Apr 30, 2009 12:08 AM
Edited by: user780731 on Apr 30, 2009 12:08 AM
Edited by: user780731 on Apr 30, 2009 12:09 AMexample:
select col1 ,order_by,case when col1 > 10 then 0 else 1 end
from tab;
select col1 ,order_by,case when col1 <> 10 then 0 else 1 end
from tab;
select col1 ,order_by,case when col1 not in (10,11,12) then 0 else 1 end
from tab;As for testing for null, decode handles that by default anyway so you can have decode or case easily..
select col1 ,order_by,decode (col1, null , 0 , 1)
from tab;
select col1 ,order_by,case when col1 is null then 0 else 1 end
from tab; -
USING NULL AND SELECT ALL IN DECODE
COL1 has the following values:
COL1
====
A
B
C
A
B
C
A
D
D
SELECT COL1 FROM TABLE1 WHERE COL1 =
DECODE(:VAL1, 'A', 'AA', 'B', 'BB', 'C', 'CC', 'D', 'DD')
1. what about the null values ? how can I add to the above statements when I enter null for the parameter :VAL1
2. what about all the values in COL1, what shall I enter for :VAL1 ?
THANKS.SELECT COL1 FROM TABLE1
WHERE nvl(COL1,0) = DECODE(:VAL1, 'A', 'AA', 'B', 'BB', 'C', 'CC', 'D', 'DD',null,0)
Can we use in this way?
Shishu Paul
Chandigarh-India -
Clearing values from request in decode method
I am using a custom table paginator. In its decode method I have the next code to control whether next link is clicked:
String pLink = (String)requestMap.get("pLink" + clientId);
if ((pLink != null) && (!pLink.equals(""))) {
if (pLink.equals("next")) {
} else if (pLink.equals("previous")) {
}But the next sequence produces some problems:
1. Initial page load.
2. Click on next link.
3. Table navigates ok to next page.
4. Reload page (push F5).
5. The previous click still remains in the request, so decode method think next link is pressed again.
6. Application abnormal behaviour arises.
So, I am trying to clear the next_link key from the request, but next code throws an UnsupportedOperationException:
String pLink = (String)requestMap.get("pLink" + clientId);
if ((pLink != null) && (!pLink.equals(""))) {
if (pLink.equals("next")) {
} else if (pLink.equals("previous")) {
requestMap.put("pLink" + clientId, "");
}Do any of you have some ideas?Hey, where are you RaymondDeCampo, rLubke, BalusC ... the masters of JSF Universe?
;-) -
This works on WinXP but not Linux. Why? It takes the first frame of an animated gif and writes a thumbnail.
GifDecoder d = new GifDecoder();
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
log.debug("reading gif");
d.read(bis);
log.debug("reading framecount");
int n = d.getFrameCount();
log.debug("read framecount" + n);
for (int i = 0; i < 1; i++) {
BufferedImage frame = d.getFrame(i); // frame i
int t = d.getDelay(i); // display duration of frame in milliseconds
log.debug("resizing frame");
File gifoutputfile = new File("gif" + i + outputthumbFilename);
BufferedImage bdest = new BufferedImage(60, 60, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bdest.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance((double) 60 / frame.getWidth(), (double) 60 / frame.getHeight());
g.drawRenderedImage(frame, at);
ImageIO.setUseCache(false);
ImageIO.write(bdest, "GIF", new File(outputthumbFilename));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
* Class GifDecoder - Decodes a GIF file into one or more frames. <br>
* <pre>
* Example:
* GifDecoder d = new GifDecoder();
* d.read("sample.gif");
* int n = d.getFrameCount();
* for (int i = 0; i < n; i++) {
* BufferedImage frame = d.getFrame(i); // frame i
* int t = d.getDelay(i); // display duration of frame in milliseconds
* // do something with frame
* </pre>
* No copyright asserted on the source code of this class. May be used for any
* purpose, however, refer to the Unisys LZW patent for any additional
* restrictions. Please forward any corrections to [email protected].
* @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's
* ImageMagick.
* @version 1.03 November 2003
public class GifDecoder {
* File read status: No errors.
public static final int STATUS_OK = 0;
* File read status: Error decoding file (may be partially decoded)
public static final int STATUS_FORMAT_ERROR = 1;
* File read status: Unable to open source.
public static final int STATUS_OPEN_ERROR = 2;
protected BufferedInputStream in;
protected int status;
protected int width; // full image width
protected int height; // full image height
protected boolean gctFlag; // global color table used
protected int gctSize; // size of global color table
protected int loopCount = 1; // iterations; 0 = repeat forever
protected int[] gct; // global color table
protected int[] lct; // local color table
protected int[] act; // active color table
protected int bgIndex; // background color index
protected int bgColor; // background color
protected int lastBgColor; // previous bg color
protected int pixelAspect; // pixel aspect ratio
protected boolean lctFlag; // local color table flag
protected boolean interlace; // interlace flag
protected int lctSize; // local color table size
protected int ix, iy, iw, ih; // current image rectangle
protected Rectangle lastRect; // last image rect
protected BufferedImage image; // current frame
protected BufferedImage lastImage; // previous frame
protected byte[] block = new byte[256]; // current data block
protected int blockSize = 0; // block size
// last graphic control extension info
protected int dispose = 0;
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
protected int lastDispose = 0;
protected boolean transparency = false; // use transparent color
protected int delay = 0; // delay in milliseconds
protected int transIndex; // transparent color index
protected static final int MaxStackSize = 4096;
// max decoder pixel stack size
// LZW decoder working arrays
protected short[] prefix;
protected byte[] suffix;
protected byte[] pixelStack;
protected byte[] pixels;
protected ArrayList frames; // frames read from current file
protected int frameCount;
static class GifFrame {
public GifFrame(BufferedImage im, int del) {
image = im;
delay = del;
public BufferedImage image;
public int delay;
* Gets display duration for specified frame.
* @param n
* int index of frame
* @return delay in milliseconds
public int getDelay(int n) {
delay = -1;
if ((n >= 0) && (n < frameCount)) {
delay = ((GifFrame) frames.get(n)).delay;
return delay;
* Gets the number of frames read from file.
* @return frame count
public int getFrameCount() {
return frameCount;
* Gets the first (or only) image read.
* @return BufferedImage containing first frame, or null if none.
public BufferedImage getImage() {
return getFrame(0);
* Gets the "Netscape" iteration count, if any. A count of 0 means repeat
* indefinitiely.
* @return iteration count if one was specified, else 1.
public int getLoopCount() {
return loopCount;
* Creates new frame image from current data (and previous frames as specified
* by their disposition codes).
protected void setPixels() {
// expose destination image's pixels as int array
int[] dest = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
// fill in starting image contents based on last image's dispose code
if (lastDispose > 0) {
if (lastDispose == 3) {
// use image before last
int n = frameCount - 2;
if (n > 0) {
lastImage = getFrame(n - 1);
} else {
lastImage = null;
if (lastImage != null) {
int[] prev = ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
System.arraycopy(prev, 0, dest, 0, width * height);
// copy pixels
if (lastDispose == 2) {
// fill last image rect area with background color
Graphics2D g = image.createGraphics();
Color c = null;
if (transparency) {
c = new Color(0, 0, 0, 0); // assume background is transparent
} else {
c = new Color(lastBgColor); // use given background color
g.setColor(c);
g.setComposite(AlphaComposite.Src); // replace area
g.fill(lastRect);
g.dispose();
// copy each source line to the appropriate place in the destination
int pass = 1;
int inc = 8;
int iline = 0;
for (int i = 0; i < ih; i++) {
int line = i;
if (interlace) {
if (iline >= ih) {
pass++;
switch (pass) {
case 2:
iline = 4;
break;
case 3:
iline = 2;
inc = 4;
break;
case 4:
iline = 1;
inc = 2;
line = iline;
iline += inc;
line += iy;
if (line < height) {
int k = line * width;
int dx = k + ix; // start of line in dest
int dlim = dx + iw; // end of dest line
if ((k + width) < dlim) {
dlim = k + width; // past dest edge
int sx = i * iw; // start of line in source
while (dx < dlim) {
// map color and insert in destination
int index = ((int) pixels[sx++]) & 0xff;
int c = act[index];
if (c != 0) {
dest[dx] = c;
dx++;
* Gets the image contents of frame n.
* @return BufferedImage representation of frame, or null if n is invalid.
public BufferedImage getFrame(int n) {
BufferedImage im = null;
if ((n >= 0) && (n < frameCount)) {
im = ((GifFrame) frames.get(n)).image;
return im;
* Gets image size.
* @return GIF image dimensions
public Dimension getFrameSize() {
return new Dimension(width, height);
* Reads GIF image from stream
* @param BufferedInputStream
* containing GIF file.
* @return read status code (0 = no errors)
public int read(BufferedInputStream is) {
init();
if (is != null) {
in = is;
readHeader();
if (!err()) {
readContents();
if (frameCount < 0) {
status = STATUS_FORMAT_ERROR;
} else {
status = STATUS_OPEN_ERROR;
try {
is.close();
} catch (IOException e) {
return status;
* Reads GIF image from stream
* @param InputStream
* containing GIF file.
* @return read status code (0 = no errors)
public int read(InputStream is) {
init();
if (is != null) {
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
in = (BufferedInputStream) is;
readHeader();
if (!err()) {
readContents();
if (frameCount < 0) {
status = STATUS_FORMAT_ERROR;
} else {
status = STATUS_OPEN_ERROR;
try {
is.close();
} catch (IOException e) {
return status;
* Reads GIF file from specified file/URL source (URL assumed if name contains
* ":/" or "file:")
* @param name
* String containing source
* @return read status code (0 = no errors)
public int read(String name) {
status = STATUS_OK;
try {
name = name.trim().toLowerCase();
if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) {
URL url = new URL(name);
in = new BufferedInputStream(url.openStream());
} else {
in = new BufferedInputStream(new FileInputStream(name));
status = read(in);
} catch (IOException e) {
status = STATUS_OPEN_ERROR;
return status;
* Decodes LZW image data into pixel array. Adapted from John Cristy's
* ImageMagick.
protected void decodeImageData() {
int NullCode = -1;
int npix = iw * ih;
int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
if ((pixels == null) || (pixels.length < npix)) {
pixels = new byte[npix]; // allocate new pixel array
if (prefix == null)
prefix = new short[MaxStackSize];
if (suffix == null)
suffix = new byte[MaxStackSize];
if (pixelStack == null)
pixelStack = new byte[MaxStackSize + 1];
// Initialize GIF data stream decoder.
data_size = read();
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = NullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = (byte) code;
// Decode GIF pixel stream.
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix;) {
if (top == 0) {
if (bits < code_size) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data block.
count = readBlock();
if (count <= 0)
break;
bi = 0;
datum += (((int) block[bi]) & 0xff) << bits;
bits += 8;
bi++;
count--;
continue;
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;
// Interpret the code
if ((code > available) || (code == end_of_information))
break;
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = NullCode;
continue;
if (old_code == NullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
in_code = code;
if (code == available) {
pixelStack[top++] = (byte) first;
code = old_code;
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
first = ((int) suffix[code]) & 0xff;
// Add a new string to the string table,
if (available >= MaxStackSize)
break;
pixelStack[top++] = (byte) first;
prefix[available] = (short) old_code;
suffix[available] = (byte) first;
available++;
if (((available & code_mask) == 0) && (available < MaxStackSize)) {
code_size++;
code_mask += available;
old_code = in_code;
// Pop a pixel off the pixel stack.
top--;
pixels[pi++] = pixelStack[top];
i++;
for (i = pi; i < npix; i++) {
pixels[i] = 0; // clear missing pixels
* Returns true if an error was encountered during reading/decoding
protected boolean err() {
return status != STATUS_OK;
* Initializes or re-initializes reader
protected void init() {
status = STATUS_OK;
frameCount = 0;
frames = new ArrayList();
gct = null;
lct = null;
* Reads a single byte from the input stream.
protected int read() {
int curByte = 0;
try {
curByte = in.read();
} catch (IOException e) {
status = STATUS_FORMAT_ERROR;
return curByte;
* Reads next variable length block from input.
* @return number of bytes stored in "buffer"
protected int readBlock() {
blockSize = read();
int n = 0;
if (blockSize > 0) {
try {
int count = 0;
while (n < blockSize) {
count = in.read(block, n, blockSize - n);
if (count == -1)
break;
n += count;
} catch (IOException e) {
if (n < blockSize) {
status = STATUS_FORMAT_ERROR;
return n;
* Reads color table as 256 RGB integer values
* @param ncolors
* int number of colors to read
* @return int array containing 256 colors (packed ARGB with full alpha)
protected int[] readColorTable(int ncolors) {
int nbytes = 3 * ncolors;
int[] tab = null;
byte[] c = new byte[nbytes];
int n = 0;
try {
n = in.read(c);
} catch (IOException e) {
if (n < nbytes) {
status = STATUS_FORMAT_ERROR;
} else {
tab = new int[256]; // max size to avoid bounds checks
int i = 0;
int j = 0;
while (i < ncolors) {
int r = ((int) c[j++]) & 0xff;
int g = ((int) c[j++]) & 0xff;
int b = ((int) c[j++]) & 0xff;
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
return tab;
* Main file parser. Reads GIF content blocks.
protected void readContents() {
// read GIF file content blocks
boolean done = false;
while (!(done || err())) {
int code = read();
switch (code) {
case 0x2C: // image separator
readImage();
break;
case 0x21: // extension
code = read();
switch (code) {
case 0xf9: // graphics control extension
readGraphicControlExt();
break;
case 0xff: // application extension
readBlock();
String app = "";
for (int i = 0; i < 11; i++) {
app += (char) block;
if (app.equals("NETSCAPE2.0")) {
readNetscapeExt();
} else
skip(); // don't care
break;
default: // uninteresting extension
skip();
break;
case 0x3b: // terminator
done = true;
break;
case 0x00: // bad byte, but keep going and see what happens
break;
default:
status = STATUS_FORMAT_ERROR;
* Reads Graphics Control Extension values
protected void readGraphicControlExt() {
read(); // block size
int packed = read(); // packed fields
dispose = (packed & 0x1c) >> 2; // disposal method
if (dispose == 0) {
dispose = 1; // elect to keep old image if discretionary
transparency = (packed & 1) != 0;
delay = readShort() * 10; // delay in milliseconds
transIndex = read(); // transparent color index
read(); // block terminator
* Reads GIF file header information.
protected void readHeader() {
String id = "";
for (int i = 0; i < 6; i++) {
id += (char) read();
if (!id.startsWith("GIF")) {
status = STATUS_FORMAT_ERROR;
return;
readLSD();
if (gctFlag && !err()) {
gct = readColorTable(gctSize);
bgColor = gct[bgIndex];
* Reads next frame image
protected void readImage() {
ix = readShort(); // (sub)image position & size
iy = readShort();
iw = readShort();
ih = readShort();
int packed = read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
interlace = (packed & 0x40) != 0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7); // 6-8 - local color table size
if (lctFlag) {
lct = readColorTable(lctSize); // read table
act = lct; // make local table active
} else {
act = gct; // make global table active
if (bgIndex == transIndex)
bgColor = 0;
int save = 0;
if (transparency) {
save = act[transIndex];
act[transIndex] = 0; // set transparent color if specified
if (act == null) {
status = STATUS_FORMAT_ERROR; // no color table defined
if (err())
return;
decodeImageData(); // decode pixel data
skip();
if (err())
return;
frameCount++;
// create new image to receive frame data
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
setPixels(); // transfer pixel data to image
frames.add(new GifFrame(image, delay)); // add image to frame list
if (transparency) {
act[transIndex] = save;
resetFrame();
* Reads Logical Screen Descriptor
protected void readLSD() {
// logical screen size
width = readShort();
height = readShort();
// packed fields
int packed = read();
gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
// 2-4 : color resolution
// 5 : gct sort flag
gctSize = 2 << (packed & 7); // 6-8 : gct size
bgIndex = read(); // background color index
pixelAspect = read(); // pixel aspect ratio
* Reads Netscape extenstion to obtain iteration count
protected void readNetscapeExt() {
do {
readBlock();
if (block[0] == 1) {
// loop count sub-block
int b1 = ((int) block[1]) & 0xff;
int b2 = ((int) block[2]) & 0xff;
loopCount = (b2 << 8) | b1;
} while ((blockSize > 0) && !err());
* Reads next 16-bit value, LSB first
protected int readShort() {
// read 16-bit value, LSB first
return read() | (read() << 8);
* Resets frame state for reading next image.
protected void resetFrame() {
lastDispose = dispose;
lastRect = new Rectangle(ix, iy, iw, ih);
lastImage = image;
lastBgColor = bgColor;
int dispose = 0;
boolean transparency = false;
int delay = 0;
lct = null;
* Skips variable length blocks up to and including next zero length block.
protected void skip() {
do {
readBlock();
} while ((blockSize > 0) && !err());
Niklas wrote:
This works on WinXP but not Linux. Why? Please don't just post reams of code without providing more context and information.
How is it failing on Linux? Wrong results? What are they? Error messages? What do they say? You need to give us some place to start looking. -
Who can decode this who ever can I will give 4 dukes cause thats all i have
who ever is the first to decode this and tell me what it says I will give you 4 duke dollars since that is all I have here it is
vs.vo.~seeing something
vszz}.vss -
SQL Expression in decode function or case statement?
Can I put SQL expressions in decode function or case statement?
For example,
select le.profile, decode( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile, 0, 'N', 'Y')
from element le;
or
select le.profile, case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0 THEN 'N'
ELSE 'Y'
from element le;
None of the above work.
Can anyone tell me how to make it work?
Is there any workaround?
Thanks,
JYou simply needed and END to your CASE statement;
SQL> with profile_data as (
select 'XXXX_AFTER' name, 1 object_id from dual),
element as (
select 1 profile from dual union all
select 2 from dual)
select le.profile,
case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0
THEN 'N'
ELSE 'Y'
END new_col
from element le
PROFILE N
1 Y
2 N -
Hi,
I'm writing an HTMLDB application that we will be using to track the number of hours that we put into a project (all projects), and I've got a routine that returns the number of hours that are possible within a given month M-F 8 hours a day. I use this value returned to indicate how many hours have been enterered.
SELECT null link, 'Still Unrecorded' itsrdescr,trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END) hoursworked
from dual
UNION
SELECT null link, wd.itsrdescr,sum(b.hoursworked) hoursworked
FROM workdetail wd, breakdowns b
WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END
GROUP by wd.itsrdescr
ORDER by hoursworked desc
What I'm wanting is something along the lines of this:
SELECT null link, 'Still Unrecorded' itsrdescr,decode((trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END)),<0,0,?????????) hoursworked
from dual
UNION
SELECT null link, wd.itsrdescr,sum(b.hoursworked) hoursworked
FROM workdetail wd, breakdowns b
WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END
GROUP by wd.itsrdescr
ORDER by hoursworked desc
which will include a decode statement to let me know when the value getting returned into hoursworked on that first column is less than zero which throws off the chart. In this particular case, it has a value of -6 which makes all my percentages go haywire. How would one code this statement to include a decode statement to find out if that sum is returning a negative number?
Hope this made sense,
TIA,
cliffHey Tyler,
Actually.... It kinda killed the server. I'm trying to figure out a way to get the following functionality in a different way. Here is the way that the query turned out using the case statement.
SELECT null link, '<b><font color="red">Still Unrecorded</font></b>' itsrdescr,
(case
when (trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END)) < 0 then 0
else
(trueworkdays(:P80_START,:P80_END)*8-(select sum(hoursworked) ihoursworked from workdetail wd, breakdowns b
WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END))
end) hoursworked
from dual
UNION
SELECT null link, wd.itsrdescr,sum(b.hoursworked) hoursworked
FROM workdetail wd, breakdowns b
WHERE wd.workdetailid = b.itsrnum and b.oid = upper(:P80_DEVELOPER) and dateworked between :P80_START and :P80_END
GROUP by wd.itsrdescr
ORDER by hoursworked desc
Any tips on what I could do to get the above functionality without killing my server.
Thx for the input
cliff -
Oracle version: 9.2.0.1.0
Procob version: 9.2.0.1.0
Cobol version: 3.1.11
O.S. version: Windows XP
We have a pro*cobol file with the next conversion rule into a select defined with a cursor.
NVL(TO_CHAR(A.F_ALTA,'YYYYMMDD'),' '),
NVL(TO_CHAR(A.F_ESTADO,'YYYYMMDD'),' '),
we store the result data through a fetch of the cursor into two variables (W-F-ALTA and W-F-ESTADO) When the program executes an insert of these two values in a target table, we define the next conversion rule:
TO_DATE(DECODE(:W-F-ALTA,' ',NULL,:W-F-ALTA),'YYYYMMDD'),
TO_DATE(DECODE(:W-F-ESTADO,' ',NULL,:W-F-ESTADO),'YYYYMMDD')
Pro*Cobol and Cobol does not have errors when we precompile and compile the program but, when we execute the generated exe file, Oracle displays the next error:
ORA-01841 (full) year must be between -4713 and +9999, and not be 0
We think that the DECODE function is not understood by the cobol or pro*cobol interpreter. If we execute the same code without the DECODE function (only with TO_DATE function) there is no errors in the execution of the program
somebody knows if there are reported problems with this DECODE function in Pro*Cobol or Cobol and how to solve them?
ThanksTO_DATE(DECODE(:W-F-ALTA,' ',NULL,:W-F-ALTA),'YYYYMMDD'),
TO_DATE(DECODE(:W-F-ESTADO,' ',NULL,:W-F-ESTADO),'YYYYMMDD')The problem is with the input values of :W-F-ALTA and :W-F-ESTADO. Using the first line as an example, what you are saying is if :W-F-ALTA is ' ', substitute it with NULL, any other value should be :W-F-ALTA, then output the TO_DATE value of whatever the result is.
So if the value of :W-F-ALTA is the wrong charater or in the wrong input format, TO_DATE function does not understand it.
See examples of success and failures below with your Bind variables substituted with typical values.
SQL> select TO_DATE(DECODE(' ',' ',NULL,'20060830'),'YYYYMMDD') from dual;
TO_DATE(D
SQL> select TO_DATE(DECODE('1999-01-01',' ','NULL','20060830'),'YYYYMMDD') from dual;
TO_DATE(D
30-AUG-06
SQL> select TO_DATE(DECODE('SHOULD_ERROR',' ','NULL','SHOULD_ERROR'),'YYYYMMDD') from dual;
select TO_DATE(DECODE('SHOULD_ERROR',' ','NULL','SHOULD_ERROR'),'YYYYMMDD') from dual
ERROR at line 1:
ORA-01841: (full) year must be between -4713 and +9999, and not be 0
SQL> select TO_DATE(DECODE('20060830',' ','NULL','20060830'),'YYYYMMDD') from dual;
TO_DATE(D
30-AUG-06
SQL> select TO_DATE(DECODE('12345678',' ','NULL','12345678'),'YYYYMMDD') from dual;
select TO_DATE(DECODE('12345678',' ','NULL','12345678'),'YYYYMMDD') from dual
ERROR at line 1:
ORA-01843: not a valid month
SQL> -
Problem using DECODE() function with a Query of Queries
I
posted
on my blog about an issue I was having trying to use the PL/SQL
DECODE() function with a Coldfusion Query of Queries. This function
works fine when you query a database for information. However, when
you query another query, it seems that CF doesn't recognize it. I
got errors stating that it found a left parenthesis where it
expected a FROM key word. Here is a simplified version of what I am
trying to do:
quote:
<!--- Simulated query; similar to what I was calling from
my database --->
<cfscript>
qOriginal = queryNew("Name,Email,CountryCode",
"VarChar,VarChar,VarChar");
newRow = queryAddRow(qOriginal, 5);
querySetCell(qOriginal, "Name", "Joe", 1);
querySetCell(qOriginal, "Email", "[email protected]", 1);
querySetCell(qOriginal, "CountryCode", "AMER", 1);
querySetCell(qOriginal, "Name", "Sally", 2);
querySetCell(qOriginal, "Email", "[email protected]", 2);
querySetCell(qOriginal, "CountryCode", "AMER", 2);
querySetCell(qOriginal, "Name", "Bob", 3);
querySetCell(qOriginal, "Email", "[email protected]", 3);
querySetCell(qOriginal, "CountryCode", "ASIA", 3);
querySetCell(qOriginal, "Name", "Mary", 4);
querySetCell(qOriginal, "Email", "[email protected]", 4);
querySetCell(qOriginal, "CountryCode", "EURO", 4);
querySetCell(qOriginal, "Name", "John", 5);
querySetCell(qOriginal, "Email", "[email protected]", 5);
querySetCell(qOriginal, "CountryCode", "EURO", 5);
</cfscript>
<cfquery name="qCountries" dbtype="query">
SELECT DISTINCT(CountryCode) AS CountryCode,
DECODE(states, "AMER", "North America & Canada",
"EURO", "Europe & Africa", "ASIA", "Japan &
Asia","") CountryName
FROM qOriginal
ORDER BY CountryCode
</cfquery>
<cfdump var="#qCountries#">
<!--- ========== END OF CODE ========== --->
So running this returned the following error:
Query Of Queries syntax error.
Encountered "(. Incorrect Select Statement, Expecting a
'FROM', but encountered '(' instead, A select statement should have
a 'FROM' construct.
Does anybody know why this doesn't work? Is it just not
supported? Please note that I have also tried to use the CASE()
function instead of DECODE() and that resulted in basically the
same error. For now I an looping over my distinct query with a
switch statement and manually loading a new query with the data how
I want it. But it would be a lot cleaner and less code to have the
DECODE() to work. Thx!DECODE() is an Oracle function, not generic SQL. Q-of-Q is a
very limited subset of SQL and lacks many functions and clauses
available in standard SQL, especially what you may be used to using
in your particular RDBMS.
See
Query
of Queries user guide
Phil -
Hi all,
i want to know abt decode function in oracle-sql
i..e passing the parameters in decode using decode using ":" bind parameter
select JOB, decode(:j,'CLERK','MANAGER','ANALYST','EXEC',JOB) FROM EMP;
i declared the j variable in sql environment
VARIABLE J VARCHAR2(20);
i exec the query
and passed as the clerk as input parameter
but iam getting the o/p as
JOB DECODE(:J
MANAGER MANAGER
MANAGER MANAGER
MANAGER MANAGER
SALESMAN SALESMAN
SALESMAN SALESMAN
SALESMAN SALESMAN
CLERK CLERK
SALESMAN SALESMAN
ANALYST ANALYST
CLERK CLERK
ANALYST ANALYST
JOB DECODE(:J
CLERK CLERK
12 rows selected.
SQL> PRINT J;
J
im not getting o/p
so please hlelp me only : should be used not &
this is my first thread.
execuse me if any mistakes
tons of thanks in advance to allSORRY DAVE,ROD FOR NOT BEING CLEAR,
IAM WORKING WITH EMP TABLE THE DATA IN IT IS LIKE THIS
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 chaitu SALESMAN 7698 20-FEB-81 1600 300 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
AND I USED DECODE FUNCTION
select JOB BEFOREPROMOTION, decode(job,'CLERK','MANAGER','ANALYST','EXEC') PROMOTION FROM EMP
BEFOREPRO PROMOTI
MANAGER
MANAGER
MANAGER
SALESMAN
SALESMAN
SALESMAN
CLERK MANAGER
SALESMAN
ANALYST EXEC
CLERK MANAGER
ANALYST EXEC
I..E ALL THE CLERKS TO MANAGERS AND SAME THING WITH ANALYST
OK
NOW I WILL SHOW U ANOTHER QUERY
select job,decode(job,'CLERK','MANAGER','ANALYST','EXEC',JOB) FROM EMP where job=&job;
Enter value for job: 'CLERK'
old 1: select job,decode(job,'CLERK','MANAGER','ANALYST','EXEC',JOB) FROM EMP where job=&job
new 1: select job,decode(job,'CLERK','MANAGER','ANALYST','EXEC',JOB) FROM EMP where job='CLERK'
JOB DECODE(JO
CLERK MANAGER
CLERK MANAGER
CLERK MANAGER
HERE OBSERVE THAT I PASSED JOB ='CLERKS AS PARAMETER AFTER EXECUTING THE QUERY
IT ASKED LIKE THIS AND SHOWED THE REPLACED VALUES
Enter value for job: 'CLERK'
AS SHOWN ABOVE
FOR THIS TO PASS VALUE
IN TO THE QUERY BY USING AMPERSAND('&')
TO TAKE INPUT AS CLERK
IT CHECKED AND RETURNED THE VALUE
IN THE SIMILAR WAY CAN I USE ":" COLON
TO PASS PARAMETERS
IN TO THE QUERY
CAN I USE IT
REGARDS,
PHANI
Edited by: user10652894 on Nov 26, 2008 3:24 AM -
Using DECODE Function to change data
I am trying to use the Decode function in a SQL statement to find a field that has a specific type, and when it finds that type, I want to blank out the results in a different field.
For example:
DECODE(ADDR_TYPE,'HOME',PHONE='') HOME_PHONEsomething like:
SQL> with t as
2 (select 219 id,
3 'BUS' addr_type,
4 '505-555-5555' phone
5 from dual
6 union
7 select 219 id,
8 'HOME' addr_type,
9 null phone
10 from dual
11 union
12 select 220 id,
13 'BUS' addr_type,
14 '101-111-1111' phone
15 from dual
16 union
17 select 220 id,
18 'HOME' addr_type,
19 null phone
20 from dual
21 union
22 select 223 id,
23 'BUS' addr_type,
24 '202-222-2222' phone
25 from dual
26 union
27 select 224 id,
28 'HOME' addr_type,
29 '303-333-3333' phone
30 from dual
31 union
32 select 225 id,
33 'BUS' addr_type,
34 null phone
35 from dual
36 union
37 select 226 id,
38 'HOME' addr_type,
39 null phone
40 from dual)
41 select a.id,
42 a.addr_type,
43 decode(a.addr_type,'BUS',phone,null) phone
44 from (select id, addr_type, phone,
45 row_number() over (partition by id order by id, decode(addr_type,'BUS',1,2)) rn
46 from t) a
47 where a.rn = 1;
ID ADDR PHONE
219 BUS 505-555-5555
220 BUS 101-111-1111
223 BUS 202-222-2222
224 HOME
225 BUS
226 HOME
6 rows selected.
SQL> -
PL/SQL URL decode function
I am looking for a pl/sql url decode function. Does not appear to be in owa_util or htp/htf. Does any one have one please?
You can use the utl_url package that provides public APIs for both encoding and recoding purposes.
-
How can i use this expression in DECODE function?
My PNO table formart is
PNO PDate PCount
P001 08/27/05 09:45 20
P001 08/27/05 09:50 10
P002 08/27/05 03:40 20
P003 08/28/05 11:00 20
P003 09/28/05 10:00 20
P003 08/27/05 11:00 10
P003 09/27/05 04:00 50
I want to display total pcount for shift1(morning) and shift2(evening) & the date is 08/27/05
PNO Shift1(08/27/2005 08:00 to 12:30) Shift2(08/27/2005 02:00 to 05:30)
P001 30 0
P002 0 20
P004 10 50
So for shift1 condition is:
pdate>=08/27/2005 08:00 and pdate<=08/27/2005 12:30
So for shift2 condition is:
pdate>=08/27/2005 02:00 and pdate<=08/27/2005 05:30
If i tried to give this expression in decode function , its not working.
Please give me the sql query to solve this problem.
Millions of thanks in advacneforgot to paste the output for a given date.
SQL> create table pno
2 (pno varchar2(32)
3 ,pdate date
4 ,pcount number)
5 /
Table created.
SQL>
SQL> insert into pno values('P001', to_Date('08/27/05 09:45', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL> insert into pno values('P001', to_Date('08/27/05 09:50', 'mm/dd/yy hh:mi') ,10)
2 /
1 row created.
SQL> insert into pno values('P002', to_Date('08/27/05 03:40', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL>
SQL> insert into pno values('P003', to_Date('08/28/05 11:00', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL> insert into pno values('P003', to_Date('09/28/05 10:00', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL> insert into pno values('P003', to_Date('08/27/05 11:00', 'mm/dd/yy hh:mi') ,10)
2 /
1 row created.
SQL> insert into pno values('P003', to_Date('09/27/05 04:00', 'mm/dd/yy hh:mi') ,50)
2 /
1 row created.
SQL> select pno,sum(pcount) "Morning Shift Count"
2 from pno
3 where to_char(pdate, 'mm/dd/yyyy hh:mi') >= '08/27/2005 08:00'
4 and to_char(pdate, 'mm/dd/yyyy hh:mi') <='08/27/2005 12:30'
5 group by pno
6 /
PNO Morning Shift Count
P001 30
P003 10
SQL> select pno,sum(pcount) "Evening Shift Count"
2 from pno
3 where to_char(pdate, 'mm/dd/yyyy hh:mi') >= '08/27/2005 02:00'
4 and to_char(pdate, 'mm/dd/yyyy hh:mi') <='08/27/2005 05:30'
5 group by pno
6 /
PNO Evening Shift Count
P002 20 -
Error while replacing IF statements with DECODE function in procedure
Hi All,
I have created a procedure which has nested IF statements. Now I want to replace the IF statements with DECODE functions to improve performance.
Procedure:
IF (var_int_sev = '0')
THEN
var_sev := '2';
ELSE
SELECT sev
INTO var_int_sev
FROM errorconfig
WHERE errorcode = var_errorcode;
var_sev := var_int_sev;
END IF;
I converted the above IF statement into DECODE function as mentioned below:
var_Sev := DECODE(var_int_sev,0,2,SELECT severity FROM errorconfig WHERE errorcode=var_ErrorCode)
But it throws below error at the select statement used inside DECODE.
Error(58,51): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + case mod new not null others <an identifier> <a double-quoted delimited-identifier> <a bind variable> avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date <a string literal with character set specification> <a number> <a single-quoted SQL string> pipe <an alternatively-quoted string literal with character set specification> <an alternativ
Can someone help me in converting the IF to DECODE in the above case. Also how can we use a select statement inside decode.instead of trying to rewrite all your code and hoping that the performance will be better, it's a better option to investigate and find out which part of your application is slow
read this:
When your query takes too long ... -
Is this a bug in decode function?????
Hi,
I'm trying run the following query and it blows with a ORA-01722. I'm dealing with the sample HR schema that comes with the database. The SQL is :
select employee_id, start_date, end_date, department_id,
decode(job_id, 'IT_PROG', 1,'AC_ACCOUNT', 2,'AC_MGR', 3,'MK_REP', 4,'ST_CLERK', 5,'AD_ASST', 6,'SA_REP', 7,'AC_ACCOUNT', 8,'other') Job_num, job_id
from job_history
blows up. This is what I get:
ORA-01722: invalid number
But strangely the below query works:
select employee_id, start_date, end_date, department_id,
decode(job_id, 'IT_PROG', '1','AC_ACCOUNT', '2','AC_MGR', '3','MK_REP', '4','ST_CLERK', '5','AD_ASST', '6','SA_REP', '7','AC_ACCOUNT', '8', 9999)Job_num, job_id
from job_history
The result of the second query in a comma delimited format is as below:
EMPLOYEE_ID,START_DATE,END_DATE,DEPARTMENT_ID,JOB_NUM,JOB_ID
102,1/13/1993,7/24/1998,60,1,IT_PROG
101,9/21/1989,10/27/1993,110,2,AC_ACCOUNT
101,10/28/1993,3/15/1997,110,3,AC_MGR
201,2/17/1996,12/19/1999,20,4,MK_REP
114,3/24/1998,12/31/1999,50,5,ST_CLERK
122,1/1/1999,12/31/1999,50,5,ST_CLERK
200,9/17/1987,6/17/1993,90,6,AD_ASST
176,3/24/1998,12/31/1998,80,7,SA_REP
176,1/1/1999,12/31/1999,80,9999,SA_MAN
200,7/1/1994,12/31/1998,90,2,AC_ACCOUNT
Any idea why this happens? I'm going bonkers. Your help is greatly appreciated.
Best Regards,
Naveen.It's a feature :) Databases generally provide type coercion for common data types assuming that the user actually meant the same value but as a different type. Hence, '1' -> 1. However, you couldn't directly convert 'A' to a relevant number as it could mean 10 in hex, 65 as an ASCII value, etc.
Maybe you are looking for
-
Passing parameter to report from form using RUN_REPORT_OBJECT method
Will you please let me know how to do this. I tried using run_product but it is giving error as too many declarations. So I decided to use RUN_REPORT_OBJECT, but no help is provided how to pass paramters to this routine from FORMS to REPORTS.
-
Cable for importing to new MacBook Pro
Could you please tell me what kind of cable connection (DV interface cable?) I should purchase for importing movies from my Panasonic (PV-GS83) to my brand new MacBook Pro? The one I have for my iBook G4 no longer works because the MacBook Pro doesn'
-
Weblogic long level settings question?
Is there a way to create error and output logs for each webapps seperately in weblogic. Currently weblogic only allows us to create a log to the server level.
-
Why do I keep getting kicked off line when I'm in the middle of something
Why is it I keep getting kicked off in the middle of doing something
-
I cannot transfer or copy pictures from Facebook to my iPad album. I tap the photo and it says save image but does not show up in my album.