Row with max date
Hi guys,
Quick question which I would appreciate some help with. I am currently querying a table with multiple rows but I only want it to return 1 row (the one which was created most recently) ie. the one with the max date_Created field.
I was thinking I could do this:
Select *
from table
where date_created = max(date_created)
but you will probably know I cant do this. I know I can partition etc but since I am calling this as a cursor from oracle forms I cant use partition, can anyone help me out please?
Thanks.
Hi,
Here's one way:
WITH got_r_num AS
SELECT t.*
, ROW_NUMBER () OVER (ORDER BY date_created DESC)
AS r_num
FROM table_x t
SELECT * -- or list all columns except r_num
FROM got_r_num
WHERE r_num = 1
786733 wrote:Hi guys,
Quick question which I would appreciate some help with. I am currently querying a table with multiple rows but I only want it to return 1 row (the one which was created most recently) ie. the one with the max date_Created field.
I was thinking I could do this:
Select *
from table
where date_created = max(date_created)
but you will probably know I cant do this. You can do something pretty close:
SELECT *
FROM table_x
WHERE date_created = (
SELECT MAX (date_created)
FROM table_x
;However, if there is a tie (that is, 2 or more rows that have exactly the same date_created, and none later), then this will return all of them, and you said you only want 1 row.
I know I can partition etc but since I am calling this as a cursor from oracle forms I cant use partition, can anyone help me out please?Sorry, I don;t undersand what you're saying about partitions.
If there's something that you can do in, say, SQL*Plus, but not in Forms, then hre's probably a way to "hide" it (in a view, perhaps) so that the part Forms can't hande isn't being done in Forms.
Similar Messages
-
Query to get row with max values for distinct
I have a table test with ID, ADID, MTMST columns.
ID ----ADID---- MTMST
1 ----100---- 24-MAR-12 08.17.09.000000 PM
1 ----101---- 24-MAR-12 08.18.15.000000 PM
1 ----102---- 24-MAR-12 08.18.56.000000 PM
2 ----103---- 24-MAR-12 08.19.21.000000 PM
2 ----104---- 24-MAR-12 08.19.36.000000 PM
2 ----105---- 24-MAR-12 08.19.46.000000 PM
3 ----99---- 22-MAR-12 09.48.22.000000 PM
I need the rows with max ADID for each ID.
I used the following query but it provided max ADID of the table but not the distinct ID
select * from test where ADID in (select max(ADID) from test where id in (select distinct(id) from test where mtmst > sysdate -1))
Result:*
ID ----ADID---- MTMST
2 ----105---- 24-MAR-12 08.19.46.000000 PM
Expected result:*
ID ----ADID---- MTMST
1 ----102---- 24-MAR-12 08.18.56.000000 PM
2 ----105---- 24-MAR-12 08.19.46.000000 PM
Thanks,
Dheepan
Edited by: Dheepan on Mar 24, 2012 9:53 AMselect id, adid, mtmst from test where (id, adid) in (select id, max(adid) from test group by id) and MTMST>sysdate-1
is the answer. -
Not Getting Rows With No Date Match
I have SQL 2012 and am trying to use a CTE to get patient meal calendar rows even if the row does not match a given date range. We use a Calendar table that has 1 row for each date in the year so I wanted it to drive the results so that when I ask for a
week date range I will get rows even if the patient does not have a meal or snack scheduled for that date. My CTE code is below and it gives me the correct data but only if the patient has a meal or snack scheduled for that date (this is like a weekly
meal menu). Any help is appreciated.
ALTER PROCEDURE [dbo].[kd_selMealPlannerMatrix]
@PatientID int,
@StartDate smalldatetime,
@EndDate smalldatetime = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF @EndDate IS NULL
BEGIN
SET @EndDate = DATEADD(day,6,@StartDate);
END
;WITH client_meals AS (
SELECT DATEPART(dw, dbo.tblMealCalendar.MealDate) AS PrintDate,
dbo.tlkpMealCodes.MealCode,
CASE WHEN dbo.tblMealCalendar.MealID <> 0 THEN dbo.tblActualMeals.MealName + N' - ' + CONVERT(nvarchar, dbo.tblActualMeals.MealNumber)
WHEN dbo.tblMealCalendar.SnackID <> 0 THEN dbo.tblActualSnacks.SnackName + N' - ' + CONVERT(nvarchar, dbo.tblActualSnacks.SnackNumber)
ELSE NULL
END AS PrintMeal,
dbo.tblMealCalendar.PatientID,
dbo.tblMealCalendar.MealDate,
dbo.tblMealCalendar.CalendarID,
dbo.tlkpMealCodes.MealCodeSort,
dbo.tblActualMeals.MealID,
dbo.tblActualSnacks.SnackID,
dbo.tblMealCalendar.MealCodeID
FROM dbo.tblMealCalendar LEFT OUTER JOIN
dbo.tblActualMeals ON dbo.tblMealCalendar.MealID = dbo.tblActualMeals.MealID LEFT OUTER JOIN
dbo.tblActualSnacks ON dbo.tblMealCalendar.SnackID = dbo.tblActualSnacks.SnackID LEFT OUTER JOIN
dbo.tlkpMealCodes ON dbo.tblMealCalendar.MealCodeID = dbo.tlkpMealCodes.MealCodeID
WHERE (dbo.tblActualSnacks.Verified IS NULL OR dbo.tblActualSnacks.Verified <> 0)
AND (dbo.tblActualMeals.Verified IS NULL OR dbo.tblActualMeals.Verified <> 0)
AND (dbo.tblMealCalendar.PatientID = @PatientID)
), dt_range AS (
SELECT dt, DW
FROM dbo.Calendar
WHERE dt BETWEEN @StartDate AND @EndDate
SELECT
MAX(M.MealDate) AS MealDate,
MAX(M.PrintDate) AS PrintDay,
MAX(D.DW) AS WkDay,
MAX(CASE WHEN MealCode = 'AM Meal' THEN PrintMeal
ELSE NULL
END) AS AMMeal,
MAX(CASE WHEN MealCode = 'AM Meal' THEN MealID
ELSE 0
END) AS AMMealID,
MAX(CASE WHEN MealCode = 'AM Snack' THEN PrintMeal
ELSE NULL
END) AS AMSnack,
MAX(CASE WHEN MealCode = 'AM Snack' THEN SnackID
ELSE 0
END) AS AMSnackID,
MAX(CASE WHEN MealCode = 'Mid-Day' THEN PrintMeal
ELSE NULL
END) AS MidDay,
MAX(CASE WHEN MealCode = 'Mid-Day' THEN MealID
ELSE 0
END) AS MidDayMealID,
MAX(CASE WHEN MealCode = 'PM Snack' THEN PrintMeal
ELSE NULL
END) AS PMSnack,
MAX(CASE WHEN MealCode = 'PM Snack' THEN SnackID
ELSE 0
END) AS PMSnackID,
MAX(CASE WHEN MealCode = 'PM Meal' THEN PrintMeal
ELSE NULL
END) AS PMMeal,
MAX(CASE WHEN MealCode = 'PM Meal' THEN MealID
ELSE 0
END) AS PMMealID,
MAX(CASE WHEN MealCode = 'Evening Snack' THEN PrintMeal
ELSE NULL
END) AS EveningSnack,
MAX(CASE WHEN MealCode = 'Evening Snack' THEN SnackID
ELSE 0
END) AS EveningSnackID,
MAX(CASE WHEN MealCode = '4th Meal' THEN PrintMeal
ELSE NULL
END) AS FourthMeal,
MAX(CASE WHEN MealCode = '4th Meal' THEN MealID
ELSE 0
END) AS FourthMealID
FROM dt_range AS D RIGHT OUTER JOIN
client_meals AS M ON D.dt = M.MealDate
GROUP BY D.dt
HAVING (D.dt BETWEEN @StartDate AND @EndDate)
ORDER BY D.dt;
ENDI tried to keep this as close to what we know as I could. Here's an example of making it work as you're asking:
DECLARE @tinyCalendar table (date date)
DECLARE @i INT = 0
WHILE @i < 10
BEGIN
INSERT INTO @tinyCalendar (date)
VALUES (DATEADD(DAY,-@i,GETDATE()))
SET @i = @i + 1
END
DECLARE @patients TABLE (id INT IDENTITY, name VARCHAR(20))
INSERT INTO @patients (name)
VALUES ('John'),('Paul'),('George'),('Ringo')
DECLARE @mealSelections TABLE (patientID INT, mealID INT, mealCode VARCHAR(8), DATE DATE)
INSERT INTO @mealSelections (patientID, mealID, mealCode, date)
VALUES
(1,1,'1st Meal','2014-08-12'),(1,2,'1st Meal','2014-08-13'),(1,3,'1st Meal','2014-08-14'),(1,4,'1st Meal','2014-08-15'),(2,1,'1st Meal','2014-08-12'),(2,2,'1st Meal','2014-08-13'),(2,3,'1st Meal','2014-08-14'),(2,4,'1st Meal','2014-08-15'),(3,1,'1st Meal','2014-08-12'),(3,2,'1st Meal','2014-08-13'),(3,3,'1st Meal','2014-08-14'),(3,4,'1st Meal','2014-08-15'),(4,1,'1st Meal','2014-08-12'),(4,2,'1st Meal','2014-08-13'),(4,3,'1st Meal','2014-08-14'),(4,4,'1st Meal','2014-08-15'),
(1,1,'1st Meal','2014-08-16'),(1,2,'1st Meal','2014-08-17'),(1,3,'1st Meal','2014-08-18'),(1,4,'1st Meal','2014-08-19'),(2,1,'1st Meal','2014-08-16'),(2,2,'1st Meal','2014-08-17'),(2,3,'1st Meal','2014-08-18'),(2,4,'1st Meal','2014-08-19'),(3,1,'1st Meal','2014-08-16'),(3,2,'1st Meal','2014-08-17'),(3,3,'1st Meal','2014-08-18'),(3,4,'1st Meal','2014-08-19'),(4,1,'1st Meal','2014-08-16'),(4,2,'1st Meal','2014-08-17'),(4,3,'1st Meal','2014-08-18'),(4,4,'1st Meal','2014-08-19'),
(1,1,'2nd Meal','2014-08-12'),(1,2,'2nd Meal','2014-08-13'),(1,3,'2nd Meal','2014-08-14'),(1,4,'2nd Meal','2014-08-15'),(2,1,'2nd Meal','2014-08-12'),(2,2,'2nd Meal','2014-08-13'),(2,3,'2nd Meal','2014-08-14'),(2,4,'2nd Meal','2014-08-15'),(3,1,'2nd Meal','2014-08-12'),(3,2,'2nd Meal','2014-08-13'),(3,3,'2nd Meal','2014-08-14'),(3,4,'2nd Meal','2014-08-15'),(4,1,'2nd Meal','2014-08-12'),(4,2,'2nd Meal','2014-08-13'),(4,3,'2nd Meal','2014-08-14'),(4,4,'2nd Meal','2014-08-15'),
(1,1,'2nd Meal','2014-08-16'),(1,2,'2nd Meal','2014-08-17'),(1,3,'2nd Meal','2014-08-18'),(1,4,'2nd Meal','2014-08-19'),(2,1,'2nd Meal','2014-08-16'),(2,2,'2nd Meal','2014-08-17'),(2,3,'2nd Meal','2014-08-18'),(2,4,'2nd Meal','2014-08-19'),(3,1,'2nd Meal','2014-08-16'),(3,2,'2nd Meal','2014-08-17'),(3,3,'2nd Meal','2014-08-18'),(3,4,'2nd Meal','2014-08-19'),(4,1,'2nd Meal','2014-08-16'),(4,2,'2nd Meal','2014-08-17'),(4,3,'2nd Meal','2014-08-18'),(4,4,'2nd Meal','2014-08-19'),
(1,1,'3rd Meal','2014-08-12'),(1,2,'3rd Meal','2014-08-13'),(1,3,'3rd Meal','2014-08-14'),(1,4,'3rd Meal','2014-08-15'),(2,1,'3rd Meal','2014-08-12'),(2,2,'3rd Meal','2014-08-13'),(2,3,'3rd Meal','2014-08-14'),(2,4,'3rd Meal','2014-08-15'),(3,1,'3rd Meal','2014-08-12'),(3,2,'3rd Meal','2014-08-13'),(3,3,'3rd Meal','2014-08-14'),(3,4,'3rd Meal','2014-08-15'),(4,1,'3rd Meal','2014-08-12'),(4,2,'3rd Meal','2014-08-13'),(4,3,'3rd Meal','2014-08-14'),(4,4,'3rd Meal','2014-08-15'),
(1,1,'3rd Meal','2014-08-16'),(1,2,'3rd Meal','2014-08-17'),(1,3,'3rd Meal','2014-08-18'),(1,4,'3rd Meal','2014-08-19'),(2,1,'3rd Meal','2014-08-16'),(2,2,'3rd Meal','2014-08-17'),(2,3,'3rd Meal','2014-08-18'),(2,4,'3rd Meal','2014-08-19'),(3,1,'3rd Meal','2014-08-16'),(3,2,'3rd Meal','2014-08-17'),(3,3,'3rd Meal','2014-08-18'),(3,4,'3rd Meal','2014-08-19'),(4,1,'3rd Meal','2014-08-16'),(4,2,'3rd Meal','2014-08-17'),(4,3,'3rd Meal','2014-08-18'),(4,4,'3rd Meal','2014-08-19'),
(1,1,'4th Meal','2014-08-12'),(1,2,'4th Meal','2014-08-13'),(1,3,'4th Meal','2014-08-14'),(1,4,'4th Meal','2014-08-15'),(2,1,'4th Meal','2014-08-12'),(2,2,'4th Meal','2014-08-13'),(2,3,'4th Meal','2014-08-14'),(2,4,'4th Meal','2014-08-15'),(3,1,'4th Meal','2014-08-12'),(3,2,'4th Meal','2014-08-13'),(3,3,'4th Meal','2014-08-14'),(3,4,'4th Meal','2014-08-15'),(4,1,'4th Meal','2014-08-12'),(4,2,'4th Meal','2014-08-13'),(4,3,'4th Meal','2014-08-14'),(4,4,'4th Meal','2014-08-15'),
(1,1,'4th Meal','2014-08-16'),(1,2,'4th Meal','2014-08-17'),(1,3,'4th Meal','2014-08-18'),(1,4,'4th Meal','2014-08-19'),(2,1,'4th Meal','2014-08-16'),(2,2,'4th Meal','2014-08-17'),(2,3,'4th Meal','2014-08-18'),(2,4,'4th Meal','2014-08-19'),(3,1,'4th Meal','2014-08-16'),(3,2,'4th Meal','2014-08-17'),(3,3,'4th Meal','2014-08-18'),(3,4,'4th Meal','2014-08-19'),(4,1,'4th Meal','2014-08-16'),(4,2,'4th Meal','2014-08-17'),(4,3,'4th Meal','2014-08-18'),(4,4,'4th Meal','2014-08-19')
SELECT p.id, p.name, c.date,
Max(CASE WHEN mealCode = '1st Meal' THEN mealID END) AS FirstMeal,
Max(CASE WHEN mealCode = '2nd Meal' THEN mealID END) AS SecondMeal,
Max(CASE WHEN mealCode = '3rd Meal' THEN mealID END) AS ThirdMeal,
Max(CASE WHEN mealCode = '4th Meal' THEN mealID END) AS FourthMeal
FROM @patients p
INNER JOIN @tinyCalendar c
ON p.id = p.id
LEFT OUTER JOIN @mealSelections m
ON p.id = m.patientID
AND m.date = c.date
GROUP BY p.id, p.name, c.date
ORDER BY c.date -
I am really stupid of this right now. Have not tried the regular SQL for long time, so my question is that I have a table- Cost
A B C D E F
0002 6002 5 55 68.35 6.12
0003 6003 5 99.26 89.33 8.23
0004 6004 5 78.85 4.4 7.42
0004 6004 6 78.85 8.1 1.7
0004 6004 7 78.85 70.9 6.73
0005 6005 5 49.88 76.1 68.53
0005 6005 6 49.88 93.7 18.57
0005 6005 7 49.88 255.7 63
How can I get the column E and F, when I want to get the row with highest order in C as result in
A B C D E F
0002 6002 5 55 68.35 6.12
0003 6003 5 99.26 89.33 8.23
0004 6004 7 78.85 70.9 6.73
0005 6005 7 49.88 255.7 63
I used the max () and group by in query as
select A, B, max(C), D
from cost
group by A,B,D
If I added the max(E) and max(F) in the SELECT, I got correct row in E but not the F.
Please help me out. Thanks.an alternative using analytic fiunctions would be:
select "A","B",max("C"),"D","E","F" from
(select "A","B","C",last_value("D") over (partition by "A","B" order by
"A","B","C" rows between unbounded preceding and unbounded following) "D",
last_value("E") over (partition by "A","B" order by
"A","B","C" rows between unbounded preceding and unbounded following) "E",
last_value("F") over (partition by "A","B" order by
"A","B","C" rows between unbounded preceding and unbounded following) "F"
from test1)
group by "A","B","D","E","F"
order by "A","B"
this appears to give a better plan on the test data but you would want to test with a larger volume, we have reduced to numbet of buffer gets but added two sorts currently these fit in memory but you may find with a larger dataset these result in disk sorts.
Chris
Autotrace output:
SQL> select * from test1 where "A"||B||"C" in (select "A"||B||Z from (select "A", B, max("C") Z from test1 group by "A",B));
A B C D E F
0002 6002 5 55 68.35 6.12
0003 6003 5 99.26 89.33 8.23
0004 6004 7 78.85 70.9 6.73
0005 6005 7 49.88 255.7 63
Execution Plan
Plan hash value: 2706139598
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 50 | 8 (25)| 00:00:01 |
|* 1 | HASH JOIN | | 1 | 50 | 8 (25)| 00:00:01 |
| 2 | TABLE ACCESS FULL | TEST1 | 8 | 192 | 3 (0)| 00:00:01 |
| 3 | VIEW | VW_NSO_1 | 8 | 208 | 4 (25)| 00:00:01 |
| 4 | HASH UNIQUE | | 8 | 104 | 4 (25)| 00:00:01 |
| 5 | HASH GROUP BY | | 8 | 104 | 4 (25)| 00:00:01 |
| 6 | TABLE ACCESS FULL| TEST1 | 8 | 104 | 3 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - access("$nso_col_1"="A"||"B"||TO_CHAR("C"))
Statistics
0 recursive calls
0 db block gets
64 consistent gets
0 physical reads
0 redo size
795 bytes sent via SQL*Net to client
381 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
4 rows processed
SQL>
SQL> select "A","B",max("C"),"D","E","F" from
2 (select "A","B","C",last_value("D") over (partition by "A","B" order by
3 "A","B","C" rows between unbounded preceding and unbounded following) "D",
4 last_value("E") over (partition by "A","B" order by
5 "A","B","C" rows between unbounded preceding and unbounded following) "E",
6 last_value("F") over (partition by "A","B" order by
7 "A","B","C" rows between unbounded preceding and unbounded following) "F"
8 from test1)
9 group by "A","B","D","E","F"
10 order by "A","B";
A B MAX("C") D E F
0002 6002 5 55 68.35 6.12
0003 6003 5 99.26 89.33 8.23
0004 6004 7 78.85 70.9 6.73
0005 6005 7 49.88 255.7 63
Execution Plan
Plan hash value: 3359524756
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 8 | 496 | 5 (40)| 00:00:01 |
| 1 | SORT GROUP BY | | 8 | 496 | 5 (40)| 00:00:01 |
| 2 | VIEW | | 8 | 496 | 4 (25)| 00:00:01 |
| 3 | WINDOW SORT | | 8 | 192 | 4 (25)| 00:00:01 |
| 4 | TABLE ACCESS FULL| TEST1 | 8 | 192 | 3 (0)| 00:00:01 |
Statistics
0 recursive calls
0 db block gets
7 consistent gets
0 physical reads
0 redo size
802 bytes sent via SQL*Net to client
381 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
4 rows processed
SQL> -
Get articles with max date only
Hello Everyone
I've got a little problem with a sql query. I got two tables and a lot of articles. The articles are listed multiple times and got different dates. I want to select the following rows:
p.productname
i.amount
i.date
The problem is, that every product only should be listed one time (something like UNIC or DISTINCT). And it should be the product with the highest date. Is there something like MAX(date) that I can use?
What I already have is...
SELECT
p.productname,
i.amount,
i.date
FROM op_inventory i
LEFT JOIN products p
ON p.ItemID = i.fk_article
Now, how can I solve my problem above?...
Greets DolliqueHmm, thx but, that didn't solve my problem.
I've just found a german website with a detailed explantion of the solution that mack gave me.
I used that one and it seems to work quite fine, expects from I somehow can't use GROUP BY. Every time I use it, it returns a Executing DB error (like before)...
I'll see if I can solve that problem...
Thx you anyway!
Toby
PS:
My code now is
SELECT
i.id,
i.amount,
i.date,
p.productname
FROM op_inventory i
LEFT JOIN products p
ON p.ItemID = i.fk_article
<!---JOIN (
SELECT
id id_m,
MAX(date) maxdate
FROM op_inventory
GROUP BY id_m
) temp
ON i.id = temp.id_m AND i.date = temp.maxdate--->
<cfoutput>#gi_where#</cfoutput>
i.date = (
SELECT MAX(o.date)
FROM op_inventory o
WHERE o.fk_article = i.fk_article
<!---GROUP BY i.id--->
And the content of #gi_where# is:
WHERE p.category = #lb_group# AND -
XML Query Help row with no data
declare @address table
AddressID int,
AddressType varchar(12),
Address1 varchar(20),
Address2 varchar(20),
City varchar(25),
AgentID int
insert into @address
select 1, 'Home', 'abc', 'xyz road', 'RJ', 1 union all
select 2, 'Office', 'temp', 'ppp road', 'RJ', 1 union all
select 3, 'Home', 'xxx', 'aaa road', 'NY', 2 union all
select 4, 'Office', 'ccc', 'oli Com', 'CL', 2 union all
select 5, 'Temp', 'eee', 'olkiu road', 'CL', 2 union all
select 6, 'Home', 'ttt', 'loik road', 'NY', 3
SELECT a.* from @address a
where a.AddressID = 1
FOR XML path('Addresses')
SELECT a.* from @address a
where a.AddressID = 9
FOR XML path('Addresses')
Issue:
As you can see for second query where AddressID = 9 is not exists so xml is not generated but
my expected result is for second query is
<Addresses>
<AddressID />
<AddressType />
<Address1 />
<Address2 />
<City />
<AgentID />
</Addresses>
Thanks in advance for all your help.First of all: Your expectation is wrong. Sorry to say that. But your SQL statement for A.AddressID = 9 does not return a row. So no row is converted. I hope you C it: void.
From the XML viewpoint:
<Addresses>
<AddressID />
<AddressType />
<Address1 />
<Address2 />
<City />
<AgentID />
</Addresses>
is equivalent to
<Addresses />
which is equivalent to
void
You C. Sorry got infeCted some how ;)
The only meaningful result in XML would be:
<Addresses ID="1">
<AddressType>Home</AddressType>
<Address1>abc</Address1>
<Address2>xyz road</Address2>
<City>RJ</City>
<AgentID>1</AgentID>
</Addresses>
<Addresses ID="9"/>
Cause now Addresses (Really? A plural form for a single entity?) transports the meaning, well there is no data (no row) for it. We tried to find it, but we failed. In opposite to
<Addresses>
<AddressID>9</AddressID>
<AddressType />
<Address1 />
<Address2 />
<City />
<AgentID />
</Addresses>
<Addresses ID="9">
<AddressType />
<Address1 />
<Address2 />
<City />
<AgentID />
</Addresses>
Which says: well, we have a row with the ID 9, but the rest of the columns is empty.
The problem is mere semantics. But it's an important difference.
Now for your problem: Why do you expect this? Where do can you work with such a kind of informationless result?
btw, as you're using already a table variable (+1), you should also use
table value constructors like
INSERT INTO @address
VALUES ( 1, 'Home', 'abc', 'xyz road', 'RJ', 1 ),
( 2, 'Office', 'temp', 'ppp road', 'RJ', 1 ),
( 3, 'Home', 'xxx', 'aaa road', 'NY', 2 ),
( 4, 'Office', 'ccc', 'oli Com', 'CL', 2 ),
( 5, 'Temp', 'eee', 'olkiu road', 'CL', 2 ),
( 6, 'Home', 'ttt', 'loik road', 'NY', 3 );
I would use a tally table, when you really need this:
DECLARE @address TABLE
AddressID INT ,
AddressType VARCHAR(12) ,
Address1 VARCHAR(20) ,
Address2 VARCHAR(20) ,
City VARCHAR(25) ,
AgentID INT
INSERT INTO @address
VALUES ( 1, 'Home', 'abc', 'xyz road', 'RJ', 1 ),
( 2, 'Office', 'temp', 'ppp road', 'RJ', 1 ),
( 3, 'Home', 'xxx', 'aaa road', 'NY', 2 ),
( 4, 'Office', 'ccc', 'oli Com', 'CL', 2 ),
( 5, 'Temp', 'eee', 'olkiu road', 'CL', 2 ),
( 6, 'Home', 'ttt', 'loik road', 'NY', 3 );
WITH n1
AS ( SELECT *
FROM ( VALUES ( 1), ( 1), ( 1), ( 1) ) Q ( n )
n2
AS ( SELECT a.n
FROM n1 a ,
n1 b ,
n1 c ,
n1 d
NumberTally
AS ( SELECT ROW_NUMBER() OVER ( ORDER BY n ) AS n
FROM n2
SELECT NT.n AS [@ID] ,
a.AddressType ,
a.Address1 ,
a.Address2 ,
a.City ,
a.AgentID
FROM NumberTally NT
LEFT JOIN @address a ON a.AddressID = NT.n
WHERE NT.n IN ( 1, 9 )
FOR XML PATH('Address');
or the void version:
DECLARE @address TABLE
AddressID INT ,
AddressType VARCHAR(12) ,
Address1 VARCHAR(20) ,
Address2 VARCHAR(20) ,
City VARCHAR(25) ,
AgentID INT
INSERT INTO @address
VALUES ( 1, 'Home', 'abc', 'xyz road', 'RJ', 1 ),
( 2, 'Office', 'temp', 'ppp road', 'RJ', 1 ),
( 3, 'Home', 'xxx', 'aaa road', 'NY', 2 ),
( 4, 'Office', 'ccc', 'oli Com', 'CL', 2 ),
( 5, 'Temp', 'eee', 'olkiu road', 'CL', 2 ),
( 6, 'Home', 'ttt', 'loik road', 'NY', 3 );
WITH n1
AS ( SELECT *
FROM ( VALUES ( 1), ( 1), ( 1), ( 1) ) Q ( n )
n2
AS ( SELECT a.n
FROM n1 a ,
n1 b ,
n1 c ,
n1 d
NumberTally
AS ( SELECT ROW_NUMBER() OVER ( ORDER BY n ) AS n
FROM n2
SELECT a.AddressID AS [@ID] ,
a.AddressType ,
a.Address1 ,
a.Address2 ,
a.City ,
a.AgentID
FROM NumberTally NT
LEFT JOIN @address a ON a.AddressID = NT.n
WHERE NT.n IN ( 1, 9 )
FOR XML PATH('Address'); -
Update row with more data - JTable with Abstracttablemodel
Hello!
I got some problems with my program, im using jtable with abstracttablemodel.
First I include content into the jtable by pressing ”New Content”, then it will pop up a dialog which I fill with information as you can see in the picture.
http://img42.imageshack.us/img42/6969/jtable.jpg
But when its done, I want to borrow it and update that row with more information as you can see if its loaned, if it is their shall be a checkbox, name and phone there. I don’t really know how to do this. Suppose I should do a similar metodh as when I’m adding and removing content. The question is how do I do that? I’ve been looking at some tips and hints on google. It seems to me that should use “fireTableRowsUpdated” but not really sure if its right and how to. When I’m borrowing the specific row I guess I need to check which row is clicked before borrowing and then fill in the information and update the table.The borrow button will also pop up a dialog with 3 fields to fill. Here is the code I wrote for adding and removing. I’ve tried with the update but its not right which I’m going to use when borrowing objects from the database. Please help!
Code from the abstracttablemodel
private ArrayList<Objects> obj = new ArrayList<Objects>();
public void add(Objects o) {
obj.add(o);
fireTableRowsInserted(obj.size()-1, obj.size()-1);
public void remove(int o) {
int index = obj.indexOf(o);
obj.remove(o);
fireTableRowsDeleted(index, index);
public void update (Objects o){
// Not sure how to do here
//int index = obj.indexOf(o);
//fireTableRowsUpdated(index,index);
}Code for the button in the main program.
if (arg.getSource() == borrow) {
// How should I do here? I need to implement the BorrowDialog, check if a row is pressed then update? How do I do that?
BorrowDialog newLoan = new BorrowDialog(frame);
if(table.getSelectedRow() == -1)
JOptionPane.showMessageDialog(frame,"Select the row before loan");
else
dir.update(newLoan.getLoan());
table.repaint();
}Code for BorrowDialog
public class BorrowDialog extends JDialog implements ActionListener {
//implements JTextFields, Buttons,Labels and Panels.
public BorrowDialog(JFrame parent) {
//Setting buttons to panels and such
public Objects getLoan(){
return loan;
public void setLoan()
// Not sure if this is right, as I leave some fields empty, will it be empty when its updating aswell?
// I tried with add data then it just will be a new row, when I will update a specific row
loan = new Objects("", "" , "" , "" , "" ,"", loanField.getText(),nameField.getText(), phoneField.getText());
public void actionPerformed(ActionEvent arg) {
if (arg.getActionCommand().equals("Save")) {
System.out.println("save");
setLoan();
dispose();
}All help is appreciated!
Edited by: iTech34 on Feb 22, 2010 3:27 AM
Edited by: iTech34 on Feb 22, 2010 3:31 AM
Edited by: iTech34 on Feb 22, 2010 3:58 AMLook up for the rest of the code!
I explained everything on the first post, so please read there so you know the problem I got.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Database implements ActionListener {
private final int WIDTH = 800;
private final int HEIGHT = 800;
private JTable table = new JTable();
private JFrame frame = new JFrame("Database");
private JButton addContent = new JButton("New content");
private JButton borrow = new JButton("Borrow");
private JButton returnObject = new JButton("Return");
private JButton remove = new JButton("Remove");
private JButton save = new JButton("Save");
private JButton load = new JButton("Load");
private JButton exit = new JButton("Exit");
private Directory dir = new Directory();
private JPanel buttonPanel = new JPanel();
private JPanel mainPanel = new JPanel();
public Database() {
// BUTTONS
buttonPanel.add(addContent);
buttonPanel.add(remove);
buttonPanel.add(borrow);
buttonPanel.add(returnObject);
buttonPanel.add(save);
buttonPanel.add(load);
buttonPanel.add(exit);
// ACTION LISTENERS
addContent.addActionListener(this);
remove.addActionListener(this);
borrow.addActionListener(this);
returnObject.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
exit.addActionListener(this);
// JTABLE
table = new JTable(dir);
table.setAutoCreateRowSorter(true);
table.setRowHeight(25);
JScrollPane JScroll = new JScrollPane(table);
// PANELS
mainPanel.setLayout(new BorderLayout());
mainPanel.add("North", buttonPanel);
mainPanel.add("Center", JScroll);
// FRAME
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public void actionPerformed(ActionEvent arg) {
if (arg.getSource() == addContent) {
Dialog newDialog = new Dialog(frame);
dir.add(newDialog.getItem());
if (arg.getSource() == remove) {
if (table.getSelectedRow() == -1)
JOptionPane.showMessageDialog(frame,"Select the row before remove");
else
dir.remove(table.getSelectedRow());
if (arg.getSource() == borrow) {
// Not sure how to do here! I need to check which row I've clicked and take that row into BorrowDialog as argument i suppose.. please explain
BorrowDialog newLoan = new BorrowDialog(frame);
if(table.getSelectedRow() == -1)
JOptionPane.showMessageDialog(frame,"Select the row before loan");
else
dir.update(newLoan.getLoan());
table.repaint();
if (arg.getSource() == returnObject) {
if (arg.getSource() == save) {
dir.writeFile();
if (arg.getSource() == load) {
Objects[] tempObject = dir.readFile("info.txt");
for (int i = 0; tempObject[i] != null; i++)
dir.add(tempObject);
if (arg.getSource() == exit){
frame.dispose();
public static void main(String[] argv) {
new Database();
}import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class BorrowDialog extends JDialog implements ActionListener {
private final int WIDTH = 300;
private final int HEIGHT = 400;
private JButton exitDialog = new JButton("Exit");
private JButton saveDialog = new JButton("Save");
private JTextField loanField = new JTextField();
private JTextField nameField = new JTextField();
private JTextField phoneField = new JTextField();
private JLabel loanLabel = new JLabel("Loan");
private JLabel nameLabel = new JLabel("Name");
private JLabel phoneLabel = new JLabel("Phone");
private JPanel eastPanel = new JPanel();
private JPanel southPanel = new JPanel();
private JPanel westPanel = new JPanel();
private GridLayout layout = new GridLayout(3, 1);
private Objects loan;
public BorrowDialog(JFrame parent) {
super(parent, "Borrow", true);
southPanel.add(saveDialog);
southPanel.add(exitDialog);
westPanel.add(loanLabel);
eastPanel.add(loanField);
westPanel.add(nameLabel);
eastPanel.add(nameField);
westPanel.add(phoneLabel);
eastPanel.add(phoneField);
westPanel.setLayout(layout);
eastPanel.setLayout(layout);
add("West", westPanel);
add("Center", eastPanel);
add("South", southPanel);
saveDialog.addActionListener(this);
exitDialog.addActionListener(this);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
setSize(WIDTH, HEIGHT);
getContentPane();
setVisible(true);
public Objects getLoan(){
return loan;
public void setLoan()
// Can I really do like this? Will the the specific row I've chosen be overwriten entirly with blank elements in the six columns as I left empty(see below, when I send the arguments into the constructor)?
loan = new Objects("", "" , "" , "" , "" ,"", loanField.getText(),nameField.getText(), phoneField.getText());
public void actionPerformed(ActionEvent arg) {
if (arg.getActionCommand().equals("Save")) {
System.out.println("save");
setLoan();
dispose();
if (arg.getSource() == exitDialog) {
dispose();
Edited by: iTech34 on Feb 22, 2010 11:19 AM
Edited by: iTech34 on Feb 22, 2010 11:20 AM -
SQL subquery returning too many rows with Max function
Hello, I hope someone can help me, I been working on this all day. I need to get max value, and the date and id where that max value is associated with between specific date ranges. Here is my code , and I have tried many different version but it still returning
more than one ID and date
Thanks in advance
SELECT
distinctbw_s.id,
avs.carProd,cd_s.RecordDate,
cd_s.milkProductionasMilkProd,
cd_s.WaterProductionasWaterProd
FROMtblTestbw_s
INNERJOINtblTestCpcd_sWITH(NOLOCK)
ONbw_s.id=cd_s.id
ANDcd_s.recorddateBETWEEN'08/06/2014'AND'10/05/2014'
InnerJoin
(selectid,max(CarVol)ascarProd
fromtblTestCp
whererecorddateBETWEEN'08/06/2014'AND'10/05/2014'
groupby
id)avs
onavs.id=bw_s.id
id RecordDate carProd MilkProd WaterProd
47790 2014-10-05 132155 0 225
47790 2014-10-01 13444 0 0
47790 2014-08-06 132111 10 100
47790 2014-09-05 10000 500 145
47790 2014-09-20 10000 800 500
47791 2014-09-20 10000 300 500
47791 2014-09-21 10001 400 500
47791 2014-08-21 20001 600 500
And the result should be ( max carprod)
id RecordDate carProd MilkProd WaterProd
47790 2014-10-05 132155 0 225
47791 2014-08-21 20001 600 500Help your readers help you. Remember that we cannot see your screen, do not know your data, do not understand your schema, and cannot test a query without a complete script. So - remove the derived table (to which you gave the alias "avs")
and the associated columns from your query. Does that generate the correct results? I have my doubts since you say "too many" and the derived table will generate a single row per ID. That suggests that your join between the first
2 tables is the source of the problem. In addition, the use of DISTINCT is generally a sign that the query logic is incorrect, that there is a schema issue, or that there is a misunderstanding of the schema. -
SSRS Matrix Issue. Expression calculating in row with no data.
I have a matrix with multiple column groups for different sales channels. With in each group there are several columns and some with expressions for calculations. The rows are based on sales reps. Now not every sales rep sells in every channel, so there
are some columns in which a rep will have no data. I want them be blank or show a 0. I can do both of those. The issue I am having is in the expressions for reps that have no data, it is still showing a calculation. It seems to populate that cell with whatever
the first result of an actual calculation is. See below. For rep D and E they have no calls or sales in this particular sales channel; however, the closing ratio is showing 30.23% (which is the closing ratio for rep A). I need this to be blank or 0 or N/A,
anything other that a wrong %. I have tried numerous iif and isnothing statements, e.g. =iif(Fields!count_of_customers.Value = 0,0,Fields!count_of_customers.Value/iif(Fields!Calls.Value = 0,1,Fields!Calls.Value)) plus other i have found on the internet
but none of them work. Can someone please help? Sorry it is not a picture of the report. They need to confirm my account before I can attach pictures. But this is the set up of the report.
Figure A
Phone Field
Rep Calls
Sales Closing Ratio
Premium Rep
Calls Sales
A 1000
323 32.3%
$100,250 A
50 5
B 200
10 5% $50,000
B 0
0
C 300
15 5% $25,000
C 25
5
D 0
0 32.3%
$0 D
300 50
E 0
0 32.3%
$0 E
100 15
F 500
100 20%
$300,000 F
0 0Hi RobTencents,
After testing the issue in my environment, I can reproduce it. To fix this issue, please try to use the expression below to instead the original one:
=iif(sum(Fields!count_of_customers.Value) = 0,0,sum(Fields!count_of_customers.Value)/iif(sum(Fields!Calls.Value) = 0,1,sum(Fields!Calls.Value)))
If there are any other questions, please feel free to ask.
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support -
Using alternate rows with Spry Data Set
Can anyone provide more information on how to implement alternate row colors with a Spry Data Set? What I have done is:
Create spry data set using HTML page as the data set
The html page that displays the data set is: <div spry:region="equipment">
In the default.css page that is linked, I added the info in note #1 below
When the page displays, no colors appear. Tried changing the colors and still no luck. Is there another step to do?
Note #1:
within the default.css, the following are declared:
#equipment odd {
background-color: #CCC;
#equipment even {
background-color: “#F2F2F2;
Note #2:
Here is a link to see the actual pages referenced above.
Any ideas? Getting frustrated!! Thanks in advance for any advice.You are going to kick yourself, but, you haven't assigned any page element the ID #equipment. The region is called that but the table or the DIV does not have an idea and your selector matches nothing...
-
Using a table alias to identify row with max timestamp for same ID, syntax?
Hello experts
I have created an alias of a table, so now I have table T1 and its alias T2. (T2 is not joined to anything in the universe currently)
I need to identify the row from T1 with the maximum timestamp for any given ID:
ID Timestamp
1 2011-01-24 16:26:00.000
1 2011-02-24 14:21:00.000
1 2011-02-24 13:49:00.000
I couldn't find anything on the SAP forums, but elsewhere suggested my approach should be thus:
1) Create a table alias (leave it free standing i.e. not joined) - DONE
2) For T1, create a dimension object named Timestamp - DONE
3) Create a seperate predefined condition icon funnel / filter - in the where clause:
T1.timestamp = (SELECT max(T2.timestamp) from T2 WHERE
T1.Key = T2.Key)
I'm stuck with the BO XI 3.1 syntax on step 3. I can't get it to parse.
In the where clause, mine starts with @select(T1\Timestamp) = max(@select(T2\Timestamp)
@where T1.Claim_no = T2.Claim_no)
Please can someone help me with the syntax so this thing will parse.
Many thanks in anticipation.
EddieHi ,
Can you try
SELECT ID, MAX(datetime) FROM T1 GROUP BY by ID
Thanks
Ponnarasu -
Cross Tab keeps suppressing rows with no data
I have a Crystal Report that is using a Cross Tab. I have 2 rows in the cross tab the first row is the Month name and the second row is the Day Number of the month, and the report will print the Month Name on the left followed by all the Calendar Day Numbers in the month.
The problem is that when there is no data for a Day Number row the entire row is not shown. So you might have day number 1, 2, 3 and then jumps to maybe 6. I found that the ones the cross tab was not showing did not contain any data. I just need the calendar day number to at least print so the days read sequentially instead of jumping to 6 or another number.
Is there any way to show the rows even if they don't contain any data?
I have right clicked and gone into the Cross Tab expert and there isn't anything checked to suppress rows. I don't understand why its still suppressing rows!
Is there a global report option that I missed that says "suppress rows when there are no records"?
Thank you all in advance,
I am using Crystal Reports XIR2 with Service Pack 4I am still not getting all rows to show up on the report. The rows that are not showing up contain no data in the cross tab but the row still needs to show.
The only reason I got it to work before was because I selected all values for the columns parameter so it brought back everything in the database that was why it was able to show all values.
I have two tables one is a date database and contains all the dates till 2012. The other is the product data which contains the product code and qty that the cross tab summarizes.
I have done a left outer join from the product data to the date database, and I am still not able to get all the dates to list for the selected time range.
I was able to get the dates to show up when I right clicked the link and modified the link properties. I chose Left Outer Join and then under Link Type I selected ">" in the database expert dialog. This brought back all the dates but the data in the report was all the same. Probably just the first record repeated all down the page.
Any ideas how to fix this problem? -
I have a problem, The scenario is that when I click any folder that si in my JTable's first row, the table is update by removing all the rows and showing only the contents of my selected folder. Right now it's not removing the rows and instead throwing exceptions. The code is attached. The methods to look are upDateTabel(...) and clearTableData(....), after clearing all my rows then I proceed on adding my data to the Jtable and inserting rows but it's not being done. May be I have a problem in my DefaultTableModel class. Please see the code below what I am doing wrong and how should I do it. Any help is appreciated.
Thanks
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class SimpleTable extends JPanel{
/** Formats the date */
protected SimpleDateFormat formatter;
/** variable to hold the date and time in a raw form for the directory*/
protected long dateDirectory;
/** holds the readable form converted date for the directories*/
protected String dirDate;
/** holds the readable form converted date for the files*/
protected String fileDate;
/** variable to hold the date and time in a raw form for the file*/
protected long dateFile;
/** holds the length of the file in bytes */
protected long totalLen;
/** convert the length to the wrapper class */
protected Long longe;
/** Vector to hold the sub directories */
protected Vector subDir;
/** holds the name of the selected directory */
protected String dirNameHold;
/** converting vector to an Array and store the values in this */
protected File directoryArray[];
/** hashtable to store the key-value pair */
protected static Hashtable hashTable = new Hashtable();
/** refer to the TableModel that is the default*/
protected MyTableModel tableModel;
/** stores the path of the selected file */
protected static String fullPath;
/** stores the currently selected file */
protected static File selectedFilename;
/** stores the extension of the selected file */
protected static String extension;
protected int COLUMN_COUNT = 4;
protected Vector data = new Vector( 0, 1 );
protected final JTable table;
/** holds the names of the columns */
protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
public SimpleTable(File directoryArray[])
this.setLayout(new BorderLayout());
this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
(SimpleTable.hashTable).clear();
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
else if(directoryArray[k].isFile())
dateDirectory = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateDirectory));
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
tableModel = new MyTableModel();
table = new JTable( tableModel );
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(false);
table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.addMouseListener(new MouseAdapter()
public void mouseReleased(MouseEvent e)
Object eventTarget = e.getSource();
if( eventTarget == table )
upDateTable(table);
table.tableChanged( new javax.swing.event.TableModelEvent(tableModel) ) ;
DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this window.
this.add(scrollPane, BorderLayout.CENTER);
* Searches the Hashtable and returns the path of the folder or the value.
public File findPath(String value)
return (File)((SimpleTable.hashTable).get(value));
* This clears the previous data in the JTable
public void clearTableData(JTable table)
for(int row = 0; row < table.getRowCount() ; row++)
//for (int col = 0; col < table.getColumnCount() ; col++)
tableModel.deleteSelections( row );
tableModel.fireTableStructureChanged();
tableModel.fireTableRowsDeleted(0,table.getRowCount());
//table.getModel().fireTableChanged(new TableModelEvent(table.getModel()));
private void upDateTable(JTable table)
if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
File argument = findPath(dirNameHold);
if(argument.isFile())
CMRDialog.fileNameTextField.setText(argument.getName());
try
fullPath = argument.getCanonicalPath();
selectedFilename = argument.getCanonicalFile();
CMRDialog.filtersComboBox.removeAllItems();
extension = fullPath.substring(fullPath.lastIndexOf('.'));
CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
catch(IOException e)
System.out.println("THE ERROR IS " + e);
return;
else if(argument.isDirectory())
String path = argument.getName();
//find the system dependent file separator
//String fileSeparator = System.getProperty("file.separator");
CMRDialog.driveComboBox.addItem(" " + path);
subDir = Search.subDirs(argument);
/**TBD:- needs a method to convert the vector to an array and return the array */
directoryArray = new File[subDir.size()];
int indexCount = 0;
/** TBD:- This is inefficient way of converting a vector to an array */
Iterator e = subDir.iterator();
while( e.hasNext() )
directoryArray[indexCount] = (File)e.next();
indexCount++;
/** now calls this method and clears the previous data */
clearTableData(table);
(SimpleTable.hashTable).clear();
//data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
else if(directoryArray[k].isFile())
dateDirectory = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateDirectory));
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
// tableModel.fireTableDataChanged();
// tableModel.fireTableRowsInserted(0,1);
table.revalidate();
table.validate();
class MyTableModel extends DefaultTableModel
int totalRows;
int totalCols;
public MyTableModel()
super();
setColumnIdentifiers (columnNames);
this.totalRows = data.size();
this.totalCols = columnNames.length;
// this will return the row count of your table
public int getRowCount()
return totalRows;
// this return the column count of your table
public int getColumnCount()
return totalCols;
// this return the data for each cell in your table
public Object getValueAt(int row, int col)
MyObj obj = (MyObj)data.elementAt( row );
if( obj != null )
if( col == 0 ) return( obj.first );
else if( col == 1 ) return( obj.last );
else if( col == 2 ) return( obj.third );
else if( col == 3 ) return( obj.fourth );
else return( "" );
return "";
// if you want your table to be editable then return true
public boolean isCellEditable(int row, int col)
return false;
// if your table is editable edit the data vector here and
// call table.tableChanged(...)
public void setValueAt(Object value, int row, int col)
protected void deleteSelections (int rows)
try
removeRow(rows);
catch(ArrayIndexOutOfBoundsException e)
System.out.println("The error in the row index " + rows);
fireTableDataChanged() ;
class MyObj
String first;
String last;
String third;
String fourth;
public MyObj( String f, String l, String t, String fo )
this.first = f;
this.last = l;
this.third = t;
this.fourth = fo;
#####################################The following code works fine but it doesn't show me the new updated date in my JTable. I tried to print the values that I am getting and it does give the values on the prompt but doesn't show me on the JTable only first two are shown and the rest of the table is filled with the same values. I don't know what's going on and am tired of this TableModel thing so pla. take a time to give me some suggestions. Thanks
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class SimpleTable extends JPanel {
/** Formats the date */
protected SimpleDateFormat formatter;
/** two-dimensional array to hold the information for each column */
protected Object data[][];
/** variable to hold the date and time in a raw form for the directory*/
protected long dateDirectory;
/** holds the readable form converted date for the directories*/
protected String dirDate;
/** holds the readable form converted date for the files*/
protected String fileDate;
/** variable to hold the date and time in a raw form for the file*/
protected long dateFile;
/** holds the length of the file in bytes */
protected long totalLen;
/** convert the length to the wrapper class */
protected Long longe;
/** Vector to hold the sub directories */
protected Vector subDir;
/** holds the name of the selected directory */
protected String dirNameHold;
/** converting vector to an Array and store the values in this */
protected File directoryArray[];
/** hashtable to store the key-value pair */
protected static Hashtable hashTable = new Hashtable();
/** refer to the TableModel that is the default*/
protected DefaultTableModel model;
/** stores the path of the selected file */
protected static String fullPath;
/** stores the currently selected file */
protected static File selectedFilename;
/** stores the extension of the selected file */
protected static String extension;
protected Vector m = new Vector(0,1);
/** holds the names of the columns */
protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
public SimpleTable(File directoryArray[])
this.setLayout(new BorderLayout());
this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
(SimpleTable.hashTable).clear();
data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
data[k][0] = directoryArray[k].getName();
data[k][2] = "File Folder";
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data[k][3] = dirDate;
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
else if(directoryArray[k].isFile())
data[k][0] = directoryArray[k].getName();
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data[k][1] = longe + " Bytes";
dateFile = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateFile));
data[k][3] = fileDate;
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
model = new DefaultTableModel();
model.addTableModelListener( new TableModelListener(){
public void tableChanged( javax.swing.event.TableModelEvent e )
System.out.println("************ I am inside the table changed method ********" );
final JTable table = new JTable(model);
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(false);
table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.addMouseListener(new MouseAdapter()
/* public void mousePressed(MouseEvent e)
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
/* if(e.getClickCount() >= 2 &&
(table.getSelectedColumn() == 0) &&
((table.getColumnName(0)).equals(columnNames[0])))
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
upDateTable(table);
public void mouseReleased(MouseEvent e)
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
/* if(e.getClickCount() >= 2 &&
(table.getSelectedColumn() == 0) &&
((table.getColumnName(0)).equals(columnNames[0]))) */
//System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
upDateTable(table);
/** set the columns */
for(int c = 0; c < columnNames.length; c++)
model.addColumn(columnNames[c]);
/** set the rows */
for(int r = 0; r < data.length; r++)
model.addRow(data[r]);
DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this window.
this.add(scrollPane, BorderLayout.CENTER);
* Returns the number of columns
public int getColumnTotal()
return columnNames.length;
* Returns the number of rows
public int getRowTotal(Object directoryArray[])
return directoryArray.length;
private void upDateTable(JTable table)
if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
File argument = findPath(dirNameHold);
if(argument.isFile())
CMRDialog.fileNameTextField.setText(argument.getName());
try
fullPath = argument.getCanonicalPath();
selectedFilename = argument.getCanonicalFile();
CMRDialog.filtersComboBox.removeAllItems();
extension = fullPath.substring(fullPath.lastIndexOf('.'));
CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
catch(IOException e)
System.out.println("THE ERROR IS " + e);
return;
else if(argument.isDirectory())
String path = argument.getName();
//find the system dependent file separator
//String fileSeparator = System.getProperty("file.separator");
CMRDialog.driveComboBox.addItem(" " + path);
subDir = Search.subDirs(argument);
/**TBD:- needs a method to convert the vector to an array and return the array */
directoryArray = new File[subDir.size()];
int indexCount = 0;
/** TBD:- This is inefficient way of converting a vector to an array */
Iterator e = subDir.iterator();
while( e.hasNext() )
directoryArray[indexCount] = (File)e.next();
indexCount++;
/** now calls this method and clears the previous data */
clearTableData(table);
(SimpleTable.hashTable).clear();
data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
m.clear();
data = null;
data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
for(int k = 0; k < directoryArray.length; k++)
if(directoryArray[k].isDirectory())
System.out.println("Inside the if part");
data[k][0] = directoryArray[k].getName();
table.setValueAt(directoryArray[k].getName(),k,0);
//model.fireTableCellUpdated(k,0);
data[k][2] = "File Folder";
table.setValueAt("File Folder",k,2);
//model.fireTableCellUpdated(k,2);
dateDirectory = directoryArray[k].lastModified();
dirDate = formatter.format(new java.util.Date(dateDirectory));
data[k][3] = dirDate;
table.setValueAt(dirDate,k,3);
//model.fireTableCellUpdated(k,3);
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
m.add(data);
model.addRow(m);
model.fireTableDataChanged();
else if(directoryArray[k].isFile())
System.out.println("******* Inside the else part *******");
data[k][0] = directoryArray[k].getName();
System.out.println("The Name is == " + data[k][0]);
table.setValueAt(directoryArray[k].getName(),k,0);
System.out.println("The table cell value of the name is == " + table.getValueAt(k,0));
//model.fireTableCellUpdated(k,0);
totalLen = directoryArray[k].length();
longe = new Long(totalLen);
data[k][1] = longe + " Bytes";
System.out.println("The length == " + data[k][1]);
table.setValueAt(longe + " Bytes",k,1);
System.out.println("The table cell value of the length is == " + table.getValueAt(k,1));
//model.fireTableCellUpdated(k,0);
dateFile = directoryArray[k].lastModified();
fileDate = formatter.format(new java.util.Date(dateFile));
data[k][3] = fileDate;
System.out.println("The modified date == " + data[k][3]);
table.setValueAt(fileDate,k,3);
System.out.println("The table cell value of the name is == " + table.getValueAt(k,3));
//model.fireTableCellUpdated(k,0);
(SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]); }
m.add(data);
model.addRow(m);
model.fireTableDataChanged();
// model.fireTableDataChanged();
// model.fireTableRowsInserted(0,1);
table.revalidate();
table.validate();
else
* Searches the Hashtable and returns the path of the folder or the value.
public File findPath(String value)
return (File)((SimpleTable.hashTable).get(value));
* This clears the previous data in the JTable
public void clearTableData(JTable table)
for(int row = 0; row < table.getRowCount() ; row++)
for (int col = 0; col < table.getColumnCount() ; col++)
table.setValueAt(null, row , col);
model.fireTableStructureChanged();
### -
Transpose row with multiple data into 3 columns / Excel Macros
Hi everyone, can you please help me with my manual intervention of transposing column data to row format?
Sample
Dates
01/01/2014
01/02/2014
01/03/2014
01/04/2014
01/05/2014
01/06/2014
01/07/2014
01/08/2014
01/09/2014
01/10/2014
01/11/2014
Name1
Value 1
Value 2
Value 3
Value 4
Value 5
Value 6
Value 7
Value 8
Value 9
Value 10
Value 11
Name2
Item1
Item2
Item3
Item4
Item6
Item7
Item8
Item9
Item10
Name3
Code1
Code2
Code4
Code5
Code6
Code7
Code8
Code9
Code10
Code11
Expected output
NAME
Date
DATA
Name1
01/01/2014
Value 1
Name1
01/02/2014
Value 2
Name1
01/03/2014
Value 3
Name1
01/04/2014
Value 4
Name1
01/05/2014
Value 5
Name1
01/06/2014
Value 6
Name1
01/07/2014
Value 7
Name1
01/08/2014
Value 8
Name1
01/09/2014
Value 9
Name1
01/10/2014
Value 10
Name1
01/11/2014
Value 11
Name2
01/01/2014
Item1
Name2
01/02/2014
Item2
Name2
01/03/2014
Item3
Name2
01/04/2014
Item4
Name2
01/05/2014
Item5
Name2
01/06/2014
Item6
Name2
01/07/2014
Item7
Name2
01/08/2014
Item8
Name2
01/10/2014
Item9
Name2
01/11/2014
Item10
Name2
01/12/2014
Item11
Name3
01/01/2014
Code1
Name3
01/02/2014
Code2
Name3
01/03/2014
Code3
Name3
01/04/2014
Code4
Name3
01/05/2014
Code5
Name3
01/06/2014
Code6
Name3
01/07/2014
Code7
Name3
01/08/2014
Code8
Name3
01/09/2014
Code9
Name3
01/10/2014
Code10
Name3
01/11/2014
Code11See my reply in
http://www.eileenslounge.com/viewtopic.php?f=27&t=17245
Regards, Hans Vogelaar (http://www.eileenslounge.com) -
Fetch the row with latest data,when multiple rows exist for same user
Hi ,
Thanks for reading the post.I have table with the follwoing data.
user requestdate createdate
jake 02/21/2006 15:33:41 02/25/2006 15:33:41
jake 04/20/2006 15:33:41 04/21/2006 15:33:41
jake 04/23/2006 15:33:41 04/24/2006 15:33:41
jill 02/21/2006 15:33:41 02/25/2006 15:33:41
jill 04/20/2006 15:33:41 04/21/2006 15:33:41
The data type of user,reqdate,createdate is varchar2.I want to write a query that
gives me all the users and his latest information.After running the query I am expecting the result
user requestdate createdate
jake 04/23/2006 15:33:41 04/24/2006 15:33:41
jill 04/20/2006 15:33:41 04/21/2006 15:33:41
I am not able to write the correct query.Need help , Thanks
PanduI am sorry Again,Here are the actual tables and the data in them.
SQL> desc test;
Name Null? Type
ID NOT NULL VARCHAR2(22)
OBJECTNAME VARCHAR2(30)
SQL> select id,objectname from test order by objectname;
ID OBJECTNAME
49 Nani
43 Nani
46 jack
41 jack
45 jack
47 jill
42 jill
7 rows selected.
SQL> desc testattr;
Name Null? Type
ID NOT NULL VARCHAR2(22)
ATTRNAME VARCHAR2(22)
ATTRVALUE VARCHAR2(22)
SQL> select * from testattr;
ID ATTRNAME ATTRVALUE
41 rdate 02/21/2006 15:33:41
41 cdate 02/25/2006 15:33:41
45 rdate 04/20/2006 15:33:41
45 cdate 04/21/2006 15:33:41
46 rdate 04/23/2006 15:33:41
46 cdate 04/24/2006 15:33:41
42 rdate 02/21/2006 15:33:41
42 cate 02/25/2006 15:33:41
47 rdate 04/20/2006 15:33:41
47 cdate 04/21/2006 15:33:41
43 rdate 04/04/2006 14:33:41
43 cdate 04/05/2006 16:33:41
49 rdate 05/03/2006 09:32:55
49 cdate 05/05/2006 07:12:55
14 rows selected.All the attributes have data type varchar2.I want to write a query that gives the following result.
objectname (attrvalue)requestdate (attrval)createdate
jack 04/23/2006 15:33:41 04/24/2006 15:33:41
jill 04/20/2006 15:33:41 04/21/2006 15:33:41
Nani 05/03/2006 09:32:55 05/05/2006 07:12:55.Thanks,Need help.
Pandu
Maybe you are looking for
-
Problem while printing in smartforms
Hi, My Login language is AR and i m trying to print English on the smart form. The string I am trying to print is "JOANNOU & PARASKEVAIDES (OVERSEAS) LTD." which is stored in company address details. But in smart form it is printing like ".OVERSEAS
-
Column hiding based on Dashboard Prompt value in OBIEE 10g
Hi, Can you please let me know, whether there is any possibility of "hiding the column based on the value selected in the Dashboard Prompt". Your suggestions are highly appreciated. Thanks & Regards Siva
-
Why the dependency of "Site settings" for the "About me"-button in the top menu?
Hello, I recently had a customer case where the customer asked why certain users couldn't see the "About me"-button in the top personal actions menu, after they clicked at the user name/avatar. Only user details, "Sign out" and "My settings" was visi
-
ISight crashes both Photo booth and iChat
Hello, My iSight camera seems to be causing issues with Photo Booth and iChat. Both these problems emerged at the same time, so I believe that they're related. iChat will login properly, but when I try to initiate video chat, the green iSight camera
-
Small problem after installing - solved
After doing a soft-raid install, I forgot to edit my ect/fstab. Of all the things to forget! Ugh The system still boots ok but because the file system in fstab is not using the raid md dev lines, I can't get write permissions, even as root and I can