Wednesday, October 31, 2012

Why doesn't Oracle SQL allow us to use column aliases in GROUP BY clauses?

It isn't just Oracle SQL, in fact I believe it is conforming to the ANSI SQL standard (though I don't have a reference for that). The reason is that the SELECT clause is logically processed after the GROUP BY clause, so at the time the GROUP BY is done the aliases don't yet exist.
Perhaps this somewhat ridiculous example helps clarify the issue and the ambiguity that SQL is avoiding:
SQL> select job as sal, sum(sal) as job
  2  from scott.emp
  3  group by job;

SAL              JOB
--------- ----------
ANALYST         6000
CLERK           4150
MANAGER         8275
PRESIDENT       5000
SALESMAN        5600
 
http://stackoverflow.com/questions/2681494/why-doesnt-oracle-sql-allow-us-to-use-column-aliases-in-group-by-clauses 

Using group by on multiple columns

"Group By X" means "put all those with the same value for X in the one group.
"Group By X, Y" means "put all those with the same values for both X and Y in the one group."
To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:
Table: Subject_Selection

Subject   Semester   Attendee
---------------------------------
ITB001    1          John
ITB001    1          Bob
ITB001    1          Mickey
ITB001    2          Jenny
ITB001    2          James
MKB114    1          John
MKB114    1          Erica
When you use a group by on the subject column only; say:
SELECT Subject, Count(*)
FROM [Subject_Selection]
GROUP BY Subject
You will get something like:
Subject    Count
------------------------------
ITB001     5
MKB114     2
...because there are 5 entries for ITB001, and 2 for MKB114
If we were to group by two columns:
SELECT Subject, Semester, Count(*)
FROM [Subject_Selection]
GROUP BY Subject, Semester
we would get this:
Subject    Semester   Count
------------------------------
ITB001     1          3
ITB001     2          2
MKB114     1          2
This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")
Hopefully that makes sense.

http://stackoverflow.com/questions/2421388/using-group-by-on-multiple-columns

Update Oracle SQL Query throwing missing right parenthesis error

You can't have an order by clause in a subquery, if you think about it there is no point having one as you don't need to influence the order of an update. If you remove the order by your query should work and the outcome would be no different to if the order by were allowed.

UPDATE  mytable
SET     node_index = 0
WHERE   rowid IN
        (
        SELECT  rid
        FROM    (
                SELECT  rowid AS rid
                FROM    mytable
                WHERE   procs_dt IS NOT NULL
                ORDER BY
                        cret_dt, prty
                )
        WHERE   rownum <= 10
        )
 
http://stackoverflow.com/questions/6764497/update-oracle-sql-query-throwing-missing-right-parenthesis-error 

Tuesday, October 30, 2012

difference before and after trigger in oracle

First, I'll start my answer by defining trigger: a trigger is an stored procedure that is run when a row is added, modified or deleted.
Triggers can run BEFORE the action is taken or AFTER the action is taken.
BEFORE triggers are usually used when validation needs to take place before accepting the change. They run before any change is made to the database. Let's say you run a database for a bank. You have a table accounts and a table transactions. If a user makes a withdrawal from his account, you would want to make sure that the user has enough credits in his account for his withdrawal. The BEFORE trigger will allow to do that and prevent the row from being inserted in transactions if the balance in accounts is not enough.
AFTER triggers are usually used when information needs to be updated in a separate table due to a change. They run after changes have been made to the database (not necessarily committed). Let's go back to our back example. After a successful transaction, you would want balance to be updated in the accounts table. An AFTER trigger will allow you to do exactly that.

http://stackoverflow.com/questions/3646110/difference-before-and-after-trigger-in-oracle

Friday, October 26, 2012

How to get first day and last date of week, month, quarter, year in Oracle

--First day of current week(sunday)
select TRUNC(SYSDATE, 'Day') from dual;
--First day of next week(sunday)
select TRUNC(SYSDATE+7 , 'Day') from dual;
--First day of previous week(sunday)
select TRUNC(SYSDATE-7 , 'Day') from dual;
--First day of current month
select TRUNC(SYSDATE , 'Month') from dual;
--First day of previous month
select TRUNC(TRUNC(SYSDATE , 'Month')-1 , 'Month') from dual;
--First day of next month
select TRUNC(LAST_DAY(SYSDATE)+1 , 'Month') from dual;
--First day of current year
select TRUNC(SYSDATE , 'Year') from dual;
--First day of previous year
select TRUNC(TRUNC(SYSDATE , 'Year')-1 , 'Year') from dual;
--First day of next year
select ADD_MONTHS(TRUNC(SYSDATE , 'Year'),12) from dual;
-- First Day of Current quater
select TRUNC(SYSDATE , 'Q') from dual;
--  First Day of Previous Quarter
select ADD_MONTHS(TRUNC(SYSDATE , 'Q'),-3) from dual;
--  First Day of Next Quarter
select ADD_MONTHS(TRUNC(SYSDATE , 'Q'),3) from dual;

--Last day of current week(sunday)
select TRUNC(SYSDATE, 'Day')+6 from dual;
--Last day of next week(sunday)
select TRUNC(SYSDATE+7 , 'Day')+6 from dual;
--Last day of previous week(sunday)
select TRUNC(SYSDATE-7 , 'Day')+6 from dual;
--Last day of current month
select LAST_DAY(TRUNC(SYSDATE , 'Month')) from dual;
--Last day of previous month
select LAST_DAY(TRUNC(TRUNC(SYSDATE , 'Month')-1 , 'Month')) from dual;
--Last day of next month
select LAST_DAY(TRUNC(LAST_DAY(SYSDATE)+1 , 'Month')) from dual;
--Last day of current year
select LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE , 'Year'),11)) from dual;
--Last day of previous year
select LAST_DAY(ADD_MONTHS(TRUNC(TRUNC(SYSDATE , 'Year')-1 , 'Year'),11)) from dual;
--Last day of next year
select LAST_DAY(ADD_MONTHS(TRUNC(TRUNC(SYSDATE , 'Year')-1 , 'Year'),-13)) from dual;
-- Last Day of Current quater
select LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE , 'Q'),2)) from dual;
--  Last Day of Previous Quarter
select TRUNC(SYSDATE , 'Q')-1 from dual;
--  Last Day of Next Quarter
select LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE , 'Q'),5)) from dual;

http://programmerslounge.blogspot.com/2011/07/how-to-get-first-day-and-last-day-of.html

Wednesday, October 24, 2012

Retrieving last record in each group from database - SQL Server 2005/2008

;with cteRowNumber as (
    select COMPUTERNAME, SERIALNUMBER, USERNAME, LASTIP, LASTUPDATE, SOURCE,
           row_number() over(partition by COMPUTERNAME order by LASTUPDATE desc) as RowNum
        from YourTable)
select COMPUTERNAME, SERIALNUMBER, USERNAME, LASTIP, LASTUPDATE, SOURCE
    from cteRowNumber
    where RowNum = 1
http://stackoverflow.com/questions/4751913/retrieving-last-record-in-each-group-from-database-sql-server-2005-2008 

Thursday, October 18, 2012

What is the difference between targetNamespace and xmlns:target?

Answered quite well over here: targetNamespace and xmlns without prefix, what is the difference?
To restate:
  • targetNamespace="" - As the current XML document is a schema this attribute defines the namespace that this schema is intended to target, or validate.
  • xmlns="" - Defines the default namespace within the current document for all non-prefixed elements (i.e no yada: in )
  • xmlns:target="" - here you are just defining your own namespace with the prefix target:, this is unrelated to the previous two special cases.

     
http://stackoverflow.com/questions/4126919/what-is-the-difference-between-targetnamespace-and-xmlnstarget

Monday, October 15, 2012

JAXB: How to unmarshall objects in lists?

On the records property add:
@XmlElementWrapper(name="records")
@XmlElement(name="data")
For more information on JAXB and collection properties see:
http://stackoverflow.com/questions/3683598/jaxb-how-to-unmarshall-objects-in-lists

Thursday, October 11, 2012

JAXB required=true doesn't seem to require

The JAXB reference implementation doesn't use this attribute for validation, it's purely there for documentation purposes. If you need to validate the documents, you need to define an XML Schema, and inject it into the Marshaller or Unmarshaller, using SchemaFactory. http://stackoverflow.com/questions/2669632/jaxb-required-true-doesnt-seem-to-require

nillable and minOccurs xsd element attributes

You need to decide whether you are thinking about XML as XML, or whether you are thinking about XML as a way to transmit Java (or other) object from here to there.
In XML, nillable permits the construction as an indicator of an explicit absent value, like an SQL NULL. This is semantically different from just . And both are distinct from nothing at all. So, when looking at XML, you have to distinguish four cases:

some content


For any Java item that inherits from Object, JAXB and other mapping technologies need a way to deal with null values. Nillable is the way to do that. If you forbid nillable on something that can be an object, toolkits will annoyingly use an array to find a way to represent absence.
On the other hand, if you have an array, keep in mind that the array itself is an object, and can be null. So, toolkit has to distinguish a zero-element array from a null.
On the other hand, if you have a primitive type (e.g. int), nillable will lead to problems, since there is no mapping from xsi:nil to a primitive.

http://stackoverflow.com/questions/1903062/nillable-and-minoccurs-xsd-element-attributes

How can I make a WebMethod parameter required

I've verified that Metro 2.0 does allow you to set @XmlElement(required=true) on a parameter. The generated xsd does not have minOccurs=0. It leaves minOccurs out of the generated xsd so it assumes the default value of 1.
You also have to upgrade your JDK by putting the JAX-WS 2.2 webservices-api.jar in the endorsed/ directory.
I posted the same question on the Java forums.
Thanks to jitu for both the answer and pointing out that minOccurs defaults to 1 so leaving it out of the .xsd has the desired effect.
When @XmlElement(required=true) is set on the parameter SoapUI no longer indicates that the parameter as optional.

http://stackoverflow.com/questions/2210346/how-can-i-make-a-webmethod-parameter-required

Wednesday, October 10, 2012

Different lib directories of JBoss

Other folders are for different sorts of shared libs. For example, if you have 10 apps using same DB driver, there is really no reason to keep one db driver jar per application (i.e. 10 jars). In that case you can simply put it into jboss/server//lib.
  • jboss/server//lib: all libs here are shared between all apps in given server config
  • jboss/common/lib: shared between all server configs
  • jboss/lib: these are libs for server itself (if I am not mistaking, they are also on your app classpath)
  • jboss/lib/endorsed: this is the same as above, only if you put a lib here, it will always be found before similar lib in jboss/lib. The idea is similar to Endorsed Standards Override Mechanism of JDK
http://stackoverflow.com/questions/3064526/different-lib-directories-of-jboss

Tuesday, October 9, 2012

How do I use Nant/Ant naming patterns?

The rules are:
  • a single star (*) matches zero or more characters within a path name
  • a double star (**) matches zero or more characters across directory levels
  • a question mark (?) matches exactly one character within a path name
Another way to think about it is double star (**) matches slash (/) but single star (*) does not.
Let's say you have the files:
  1. bar.txt
  2. src/bar.c
  3. src/baz.c
  4. src/test/bartest.c
Then the patterns:
  • *.c             matches nothing (there are no .c files in the current directory)
  • src/*.c     matches 2 and 3
  • */*.c         matches 2 and 3 (because * only matches one level)
  • **/*.c       matches 2, 3, and 4 (because ** matches any number of levels)
  • bar.*         matches 1
  • **/bar.*   matches 1 and 2
  • **/bar*.* matches 1, 2, and 4
  • src/ba?.c matches 2 and 3    
http://stackoverflow.com/questions/69835/how-do-i-use-nant-ant-naming-patterns

Monday, October 8, 2012

What does the SQL # symbol mean and how is it used?

They normally prefix temporary tables.
From the docs...
Prefix local temporary table names with single number sign (#table_name), and prefix global temporary table names with a double number sign (##table_name).

http://stackoverflow.com/questions/3166117/what-does-the-sql-symbol-mean-and-how-is-it-used

What does 2 periods after DB name mean?

That just means that the default schema (dbo) should be used. In other words:
Customers..FirstName

is the same thing as
Customers.dbo.FirstName
 
http://www.sqlservercentral.com/Forums/Topic585446-338-1.aspx#bm585453 

command line print file names to output file

Not much different than Linux.
dir *.pdf > fileyouwant.txt
If you only want the filenames, you can do that with
dir/b *.pdf > fileyouwant.txt
If you also want subdirs,
dir/s/b *.pdf > fileyouwant.txt
If you aren't in that directory to start with
dir/s/b C:\Path\*.pdf > fileyouwant.txt
 
http://stackoverflow.com/questions/4515510/command-line-print-file-names-to-output-file 

How does basic HTTP Auth work?

The server sends back a header stating it requires authentication for a given realm. The user provides the username and password, which the browser concatenates (username + ":" + password), and base64 encodes. This encoded string is then sent using a "Authorization"-header on each request from the browser. Because the credentials are only encoded, not encrypted, this is highly insecure unless it is sent over https.

http://security.stackexchange.com/questions/755/how-does-basic-http-auth-work

Sunday, October 7, 2012

Stub vs. Skeleton

Stubs and Skeletons 
RMI uses a standard mechanism (employed in RPC systems) for communicating with remote objects: stubs and skeletons. A stub for a remote object acts as a client's local representative or proxy for the remote object. The caller invokes a method on the local stub which is responsible for carrying out the method call on the remote object. In RMI, a stub for a remote object implements the same set of remote interfaces that a remote object implements. 

When a stub's method is invoked, it does the following: 

1) initiates a connection with the remote JVM containing the remote object, 
2) marshals (writes and transmits) the parameters to the remote JVM, 
3) waits for the result of the method invocation, 
4) unmarshals (reads) the return value or exception returned, and 
5) returns the value to the caller. 

The stub hides the serialization of parameters and the network-level communication in order to present a simple invocation mechanism to the caller. 

In the remote JVM, each remote object may have a corresponding skeleton (in Java 2 platform-only environments, skeletons are not required). 

The skeleton is responsible for dispatching the call to the actual remote object implementation. 

When a skeleton receives an incoming method invocation it does the following: 

1) unmarshals (reads) the parameters for the remote method, 
2) invokes the method on the actual remote object implementation, and 
3) marshals (writes and transmits) the result (return value or exception) to the caller. 

In the Java 2 SDK, Standard Edition, v1.2 an additional stub protocol was introduced that eliminates the need for skeletons in Java 2 platform-only environments. Instead, generic code is used to carry out the duties performed by skeletons in JDK1.1. Stubs and skeletons are generated by the rmic compiler. 

Reference: 
http://java.sun.com/j2se/1.5.0/docs/guide/rmi/spec/rmi-arch2.html

http://www.coderanch.com/t/443307/Web-Services/java/Stub-vs-Skeleton

Thursday, October 4, 2012

Java classpath and directories

The java classpath and directories has always been quite a sad story. Of course you were always able to pass a directory of classes to the jvm like this:
java -classpath classes Main
But what you usually deal with these days are jars. Often quite a bunch of them. So fair enough – let’s add a directory with jars as well:
java -classpath classes:lib Main
Up until java 5 all you got was a ClassNotFoundException because java did not search for jars but classes in there. It just ignored the jars. So what pretty much everyone ended up doing is providing yet another shell script to build up the classpath and pass it to the jvm via command line. Of course for bigger projects this let to…
java -classpath lib/commons-logging-1.1.1.jar:lib/commons-jci-core-1.0.jar:commons-io-1.2.jar:lib/junit-3.8.2.jar:lib/maven-project-2.0.8.jar:lib/rhino-js-1.6.5.jar: ...
I guess you see where I am going …an unmanageable mess of a command line. But thankfully times have changed. Starting with java 6 (mustang) you can now use wildcards in the classpath:
java -classpath classes:lib/'*' Main
Naturally this means that the order of the jars is implicit. Which in turn means you need to be extra careful when there are classpath clashes. But in general I think this is a nice feature that should have been there from day one …and I just found out about it.

http://vafer.org/blog/20081203024812/

EJB - confused about Home/Remote — LocalHome/Local interfaces

Home is responsible for the creation of the Remote (kind of like its constructor) and LocalHome and Local have the same relationship.
In each case the container is giving you a proxy that references the real EJB class that you write.
If I had to guess, what the question was looking for was the use of remote for the session bean and local for the entity bean.
Anyway, although these concepts can still exists, things have been much better simplified in EJB3.
EDIT: In response to the comment, with EJB3, the bean class itself can implement the remote and the home interfaces directly (for the session beans). They are made EJB's with a single annotation. Stateful beans have a couple more annotations to deal with state issues. Entity beans do not have a Home interface, and do not need a local interface, you can interact with the java object directly. There is an EntityManager that retrieves the right entity beans based on a query, and that EntityManager is injected via an annotation.
That kind of sums it up in a paragraph. There are great tutorials on the web for this stuff, but EJBs in general solve a class of problem that is hard to appreciate unless you deal with the problem. They aren't the only way to solve it, but unless you deal with this type of programming, just reading about it won't really help you relate to it.

http://stackoverflow.com/questions/913267/ejb-confused-about-home-remote-localhome-local-interfaces?rq=1

Tuesday, October 2, 2012

How to calculate percentage with a SQL statement

  1. The most efficient (using over()).
    select Grade, count(*) * 100.0 / sum(count(*)) over()
    from MyTablegroup by Grade
  2. Universal (any SQL version).
    select Rate, count(*) * 100.0 / (select count(*) from MyTable)
    from MyTablegroup by Rate;
    
  3. With CTE, the least efficient.
    with t(Rate, RateCount) as ( 
        select Rate, count(*) 
        from MyTable
        group by Rate)
    select Rate, RateCount * 100.0/(select sum(RateCount) from t)
    from t;
http://stackoverflow.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement