I get an error when i do the following:
SELECT *
from cGift c1 left join
(select c2.gidnumb, "t" new from cGift c2 where c2.gidnumb =
(select c3.gidnumb from cgift c3 where c3.id = c2.id and c3.date =
(select min(c4.date) from cgift c4 where c2.id == c4.id ))) tNew
on tNew.gidnumb = c1.gidnumb
Basically i have the table cgift with a list of donations on it. I need a query that return cgift with an extra column containing either “t” or null. The first donation (cgift.date) of each donor (cgift.id) should be “t”, the rest null.
Example:
gidnumb..id....date......new
10.......1.....2/1/2010..null
11.......2.....1/1/2010..t
12.......3.....1/1/2010..t
13.......1.....3/1/2010..null
14.......2.....2/1/2010..null
15.......4.....1/1/2010..t
16.......1.....1/1/2010..t
The nulls could be blancs or f or wtvr.
Can anyone tell me what’s wrong with my query, it’s driving me nuts.
I think the following should work in pretty much any SQL product:
UPDATE (addressing additional criteria):
If a person may donate more than once on
MIN(date)and you only want one donation to be marked witht, you could, for instance, do this:That is, the innermost query finds minimum days for every person, like in the previous solution, but then it also details the list with specific
gidnumbvalues, making sure that only one row per person will match this list in thecGifttable.That query should still be runnable in any DBMS. It might well be less efficient, given the double grouping. Here’s an alternative, which also uses only standard SQL, no vendor-specific features (it should also be a bit more flexible than the previous query):
As you can see, the
isfirstcolumn is calculated using a self-test on the table: if there’s no row in this table with the sameidand either earlier date or, if the date is the same, lessergidnumb, this row should be marked ast. In the absence ofELSEpart of theCASE,ELSE NULLis implied. You can, if you like add something likeELSE 'f'.Still, your SQL product might possess features which you could benefit from by constructing a possibly simpler and more efficient query. Some products, for instance, support ranking functions (which are part of SQL standard too already, it’s just that they are not universally supported yet), and here’s what you could do with a ranking function called
ROW_NUMBER():This query ranks rows partitioning them by
idand sorting first bydate, then bygidnumb. Every row with the ranking of1in this case becomes the one that should be distinguished witht.