Need a query to merge output in a single row?
Hi All,
I need a query to merge output in a single row.
Query :
Select dname from dept.
Actual output is :
Dname
EDP
ACCOUNT
GR
Desired Output is:
Dname
EDP ACCOUNT GR
Please provide me the solution
Thanks
Amit
select max(sys_connect_by_path (t.name,' ')) from ( select id,
name,
group_id,
row_number() over (partition by group_id order by id) rn
from ( select 1 id, 'test' name, 1 group_id from dual
union
select 2 id, 'test1' name, 1 group_id from dual
union
select 3 id, 'test2' name, 1 group_id from dual
union
select 4 id, 'test3' name, 1 group_id from dual) ) t
start with t.rn = 1 and id = 1
connect by t.rn = prior t.rn + 1
group by t.group_id
Similar Messages
-
Output as a single row with values separated by comas
I have a query that returns one column as:
Col1
a
b
c
I want the output as a single row with values separated by comas:
Col1
a,b,c
How do I do it in SQL?Or... build your own aggregation function :
SQL> create or replace type AggregateStr as object
2 (
3 tag VARCHAR2(1),
4 str VARCHAR2(4000), -- concatenation string
5 static function ODCIAggregateInitialize(sctx IN OUT AggregateStr) return number,
6 member function ODCIAggregateIterate(self IN OUT AggregateStr, value IN VARCHAR2) return number,
7 member function ODCIAggregateTerminate(self IN AggregateStr, returnValue OUT VARCHAR2, flags IN number) return number,
8 member function ODCIAggregateMerge(self IN OUT AggregateStr, ctx2 IN AggregateStr) return number
9 );
10 /
Type created.
Elapsed: 00:00:00.00
SQL>
SQL> create or replace type body AggregateStr is
2 static function ODCIAggregateInitialize(sctx IN OUT AggregateStr) return number is
3 begin
4 sctx := AggregateStr(',','');
5 return ODCIConst.Success;
6 end;
7
8 member function ODCIAggregateIterate(self IN OUT AggregateStr, value IN VARCHAR2) return number is
9 begin
10 self.str:=self.str||value||self.tag;
11 return ODCIConst.Success;
12 end;
13
14 member function ODCIAggregateTerminate(self IN AggregateStr, returnValue OUT VARCHAR2, flags IN number) return number is
15 begin
16 returnValue := rtrim(self.str,',');
17 return ODCIConst.Success;
18 end;
19
20 member function ODCIAggregateMerge(self IN OUT AggregateStr, ctx2 IN AggregateStr) return number is
21 begin
22 self.str := ctx2.str;
23 return ODCIConst.Success;
24 end;
25 end;
26 /
Type body created.
Elapsed: 00:00:00.00
SQL>
SQL> CREATE OR REPLACE FUNCTION ConcateStr (input VARCHAR2) RETURN VARCHAR2
2 PARALLEL_ENABLE AGGREGATE USING AggregateStr;
3 /
Function created.
Elapsed: 00:00:00.00
SQL>
SQL> select max(concate_string) keep (dense_rank last order by length(concate_string)) as concate_string
2 from (select ConcateStr(ename) over (order by ename) concate_string
3 from emp);
CONCATE_STRING
ADAMS,ALLEN,BLAKE,CLARK,FORD,JAMES,JONES,KING,MARTIN,MILLER,SCOTT,SMITH,TURNER,WARD
Elapsed: 00:00:00.00Or if you doesn't matter of the order :
SQL> select ConcateStr(ename)
2 from emp;
CONCATESTR(ENAME)
SMITH,ALLEN,WARD,JONES,MARTIN,BLAKE,CLARK,SCOTT,KING,TURNER,ADAMS,JAMES,FORD,MILLERNicolas.
adding the second query.
Message was edited by:
N. Gasparotto -
How to modify the query to get the output in a single row
Hi All,
Below is the query i have written it works fine
select DISTINCT right(left(CTACCT,13),4) AS LocationNum,
tODS_GLBalance.FiscalYearId AS FiscalYearId,
tODS_GLBalance.FiscalMonthOfYearId AS FiscalMonthOfYearId,
--tods_GLMetadata.Metric,
Case when
tods_GLMetadata.Metric = 'Gross Margin'
Then SUM(Balance)
Else 0
END AS GrossMargin,
Case when
tods_GLMetadata.Metric = 'Occupancy'
Then SUM(Balance)
Else 0
END AS Occupancy,
Case when
tods_GLMetadata.Metric = 'Payroll Dollars'
Then SUM(Balance)
Else 0
END AS Payroll,
Case when
tods_GLMetadata.Metric = 'CF Sales'
Then SUM(Balance)
Else 0
END AS OperatingSales,
Case when
tods_GLMetadata.Metric = 'Operations'
Then SUM(Balance)
Else 0
END AS OperatingExpenses
-- 0 as payroll
from ods.[JJill].[tODS_GLBalance]
inner join ods.Staging.tODS_INF_GLPCT ON tODS_GLBalance.PageNum = tODS_INF_GLPCT.CTPAGE
inner join ods.JJill.tods_GLMetadata ON tods_GLMetadata.AcctDescription = tODS_INF_GLPCT.CTDESC
where
(tODS_GLBalance.FiscalYearId = 2012) and
(tODS_GLBalance.FiscalMonthOfYearId = 2) and
(right(left(CTACCT,13),4)= 3020)
group by
right(left(CTACCT,13),4),
tODS_GLBalance.FiscalYearId,
tODS_GLBalance.FiscalMonthOfYearId,
tods_GLMetadata.Metric
This is the sample output,
LocationNum FiscalYearId FiscalMonthOfYearId GrossMargin Occupancy Payroll OperatingSales OperatingExpenses
3020 2012 2 -112477.00 0.00 0.00 0.00 0.00
3020 2012 2 0.00 0.00 0.00 -158288.94 0.00
3020 2012 2 0.00 0.00 0.00 0.00 5625.44
3020 2012 2 0.00 0.00 24185.79 0.00 0.00
3020 2012 2 0.00 31075.53 0.00 0.00 0.00
But, i am expecting the output to be something like this
LocationNum FiscalYearId FiscalMonthOfYearId GrossMargin Occupancy Payroll OperatingSales OperatingExpenses
3020 2012 2 -112477.00 31075.53 24185.79 -158288.94 5625.44
Can someone please help me with changing my query to get the desired output?
Please let me know if you have any questions.
ThanksTry this:
SELECT DISTINCT
RIGHT(LEFT(CTACCT,13),4) AS LocationNum, tODS_GLBalance.FiscalYearId AS FiscalYearId, tODS_GLBalance.FiscalMonthOfYearId AS FiscalMonthOfYearId,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Gross Margin' THEN Balance ELSE 0 END ) AS GrossMargin,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Occupancy' THEN Balance ELSE 0 END ) AS Occupancy,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Payroll Dollars' THEN Balance ELSE 0 END ) AS Payroll,
SUM(CASE WHEN tods_GLMetadata.Metric = 'CF Sales' THEN Balance ELSE 0 END ) AS OperatingSales,
SUM(CASE WHEN tods_GLMetadata.Metric = 'Operations' THEN Balance ELSE 0 END ) AS OperatingExpenses
FROM ods.[JJill].[tODS_GLBalance]
INNER JOIN ods.Staging.tODS_INF_GLPCT
ON tODS_GLBalance.PageNum = tODS_INF_GLPCT.CTPAGE
INNER JOIN ods.JJill.tods_GLMetadata
ON tods_GLMetadata.AcctDescription = tODS_INF_GLPCT.CTDESC
WHERE tODS_GLBalance.FiscalYearId = 2012
AND tODS_GLBalance.FiscalMonthOfYearId = 2
AND RIGHT(LEFT(CTACCT,13),4) = 3020
GROUP BY right(left(CTACCT,13),4), tODS_GLBalance.FiscalYearId, tODS_GLBalance.FiscalMonthOfYearId, tods_GLMetadata.Metric -
Outputing Total Numbers of Rows Returned in query using a CTE
The query below is not being parsed by SQL Server and I can understand that the column name needs to be aliased which I have equally done. The idea behind the query is to output the count of rows using a CTE.
USE AdventureWorks2012
DECLARE @TotalRows INT = 0 -- OUTPUT
WITH Invoice AS (
SELECT @TotalRows = COUNT(CustomerID)
, SalesOrderID
, CustomerID
, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '2007/07/01'
GROUP BY SalesOrderID
, CustomerID
, OrderDate
SELECT c.CustomerID
, Invoice.SalesOrderID
, Invoice.OrderDate
FROM Sales.Customer AS c
INNER JOIN Invoice
ON c.CustomerID = Invoice.CustomerID
ORDER BY Invoice.OrderDate DESC;
How do I modify the query to produce the desired retult?
Thank you.
ZionliteZionlite,
check this>?
DECLARE @TotalRows INT = 0 -- OUTPUT
;WITH Invoice AS
SELECT COUNT(CustomerID) over()
as customer_count
, SalesOrderID
, CustomerID
, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '2001/07/01'
GROUP BY SalesOrderID
, CustomerID
, OrderDate
SELECT c.CustomerID
, Invoice.SalesOrderID
, Invoice.OrderDate
, customer_count
FROM Invoice
LEFT JOIN Sales.Customer AS c
ON c.CustomerID = Invoice.CustomerID
ORDER BY Invoice.OrderDate DESC;
So the above query, gives you the rows_count as a seprate column itself. Now you may use this to update the variable by pushing the results to a temp table and selecting the column value.
Method 2:
Another method can be using the rowcount method..
DECLARE @TotalRows INT = 0 -- OUTPUT
;WITH Invoice AS
SELECT SalesOrderID
, CustomerID
, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '2001/07/01'
GROUP BY SalesOrderID
, CustomerID
, OrderDate
SELECT c.CustomerID
, Invoice.SalesOrderID
, Invoice.OrderDate
FROM Invoice
LEFT JOIN Sales.Customer AS c
ON c.CustomerID = Invoice.CustomerID
ORDER BY Invoice.OrderDate DESC;
select @totalrows=@@rowcount
select @TotalRows
Thanks,
Jay
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'> -
Oracle query - Merging multiple rows into a single row output
Hi All,
I have to have a multiple row output to be converted into a single row output.My current output looks as follows:
ID YR INC_CODE OFFN SCHOOLNO
8006 2002 00175 SC03 12
8006 2002 00175 DC06 12
8006 2002 00175 DC03 12
8006 2002 00175 DC02 12
ID,INCIDENT CODE,OFFENSE are all Primary keys
So I need the output as follows:(IN ONE ROW)
ID YR INC_CODE OFFN1 OFFN2 OFFN3 OFFN4 SCHOOLNO
8006 2002 00175 SC03 DC06 DC03 DC02 12
Can you help me on this since have been spinning the wheel and this has to be a query since will have couple of tables join to produce a materialized view.
Thanks in advanceHi Nigel,
Thanks for the reply I tested out the portion having the decode and I get the output as follows:
ID YR INC_CODE OFFN1 OFFN2 OFFN3 OFFN4 OFFN5
8982 2002 2175 DOC01 -----------------------
8982 2002 2175 DOC02-------------------
8982 2002 2175 DOC03------------
8982 2002 2175 DOC06-------
8982 2002 2175 SCV03
There is no value as max for OFFN and each INC_CODE MAY HAVE UP TO A MAX OF 5 OFFN.My query is as follows:
select distinct STU_STUDENT_ID, INC_BEG_SCH_YR,INC_INCIDENT_CODE
, decode(rank() over (partition by INC_CODE order by OFFN),1,OFFN,null) as offn1
, decode(rank() over (partition by INC_CODE order by OFFN),2,OFFN,null) as offn2
, decode(rank() over (partition by INC_CODE order by OFFN),3,OFFN,null) as offn3
, decode(rank() over (partition by INC_CODE order by OFFN),4,OFFN,null) as offn4
, decode(rank() over (partition by INC_CODE order by OFFN),5,OFFN,null) as offn5
from stu_offn where
stu_offn.ID = '8982' and stu_offn.INC_CODE = '2175'
(****Where clause is just given to just check a value)
So as you know I need to just have all the OFFN in a single row ie as follows:
ID YR INC_CODE OFFN1 OFFN2 OFFN3 OFFN4 OFFN5
8982 2002 2175 DOC01 DOC02 DOC03 DOC06 SCV03
Can you just give me a step by step procedure to go through this and the table in this case is just 'STU_OFFN'
Thanks for the earlier reply appreciate it!
****Sending this again to show the exact way the output is coming -
Need MDX query to find something like date diff and Date Range for last 10 days
Hi ,
I need two Query .First Query for below;
I have below data in table like.
Cat StartDate EndDate
A 2000-01-01 2000-01-15
B 2000-01-02 2000-01-30
C 2000-01-01 2000-01-31
D 2000-02-01 2000-02-28
A 2000-01-10 2000-01-31
I need if Startdate and Date completes whole one month then set status =1 else 0 using MDX query.
like this ;
Cat StartDate EndDate Status
A 2000-01-01 2000-01-15 1
B 2000-01-02 2000-01-30 0
C 2000-01-01 2000-01-31 1
D 2000-02-01 2000-02-28 1
A 2000-01-10 2000-01-31 1
In second query I need last 10 days from current days like;
Now = 8/20/2014
output will be ;
8/20/2014
8/19/2014
8/18/2014
8/17/2014
8/16/2014
8/15/2014
8/14/2014
8/13/2014
8/12/2014
8/11/2014
8/10/2014
Please help me .
ThanksHi Prajapati,
In your scenario, you can use Properties and Datediff function to achieve your requirement. Since not know the structure of your cube, we cannot give you the esact query.
I have tested it on the AdventureWorks cube, the query below is for you reference.
WITH MEMBER [Measures].[StartDate]
AS
[Employee].[Employee Department].CURRENTMEMBER.PROPERTIES('Start Date')
MEMBER [Measures].[WorkYear]
AS
DATEDIFF('yyyy',[Measures].[StartDate],NOW())
MEMBER [Measures].[Status]
AS
IIF(DATEDIFF('yyyy',[Measures].[StartDate],NOW())>10,1,0)
SELECT {[Measures].[StartDate],[Measures].[WorkYear],[Measures].[Status]} ON 0,
[Employee].[Employee Department].[Employee].MEMBERS ON 1
FROM [Adventure Works]
Results
Reference
http://msdn.microsoft.com/en-us/library/ms144821.aspx
Regards,
Charlie Liao
TechNet Community Support -
Create SP that returns value and at the same time displays query result in output window
I would like create an SP which will return the records from the table and also return value to my c# client application.
For Example:
Select * from employee returns all the query results in output window.
Now I want to create an SP
Create procedure Test
As
Declare @ret int,
Select * from employee
set @ret = Select count(*) from employee
if @ret > 0
return 1
else
return 0
The above algo should return 1 0r 0 to c# client application and at the same time display all employees in sql query output window.
Can u pls help in this regard.The above algo should return 1 0r 0 to c# client application and at the same time display all employees in sql query output window.
Why? and No!
Why? Your procedure generates a resultset of some number of rows. You check the resultset for the presence of rows to determine if "anything is there". You don't need a separate value to tell you this. Note that it helps
to post tsql that is syntactically correct. While we're at it, if you just need to know that rows exist there is no need to count them since that does more work than required. Simply test for existence using the appropriately-named function
"exists". E.g., if exists (select * from dbo.employee).
No! A stored procedure does not display anything anywhere. The application which executes the procedures is responsible for the consumption of the resultset; it chooses what to do and what to display.
Lastly, do not get into the lazy habit of using the asterisk in your tsql code. That is not best practice. Along with that, you should also get into the following best practice habits:
schema-qualify your objects (i.e., dbo.employee)
terminate every statement - it will eventually be required. -
Need a query to do row to column transformation
SELECT friday_date FROM t2;Table Data:
1/2/2009
1/9/2009
1/16/2009.......
I need a query to get the output in below fashion
Column
1/2/2009,1/9/2009,1/16/2009
I tried PIVOT and TRANSPOSE, cannot do this. I believe because it is a date,may be.
I tried below code also, but CONNECT_BY_ISLEAF wont work on "ORA-00904: "CONNECT_BY_ISLEAF": invalid identifier"
SELECT ltrim(sys_connect_by_path(FRIDAY_DATE,','),',') FRIDAY_DATE
FROM (
SELECT row_number() OVER(ORDER BY FRIDAY_DATE) rno,
FRIDAY_DATE
FROM t2
WHERE CONNECT_BY_ISLEAF = '1'
start WITH rno = '1'
connect BY rno = PRIOR rno+1;Thank YouSQL> WITH t2 AS ( SELECT TO_CHAR (
NEXT_DAY (
DATE '2009-01-01' + (LEVEL - 1) * 7,
'friday'
'mm/dd/yyyy'
friday_date
FROM DUAL
CONNECT BY LEVEL <= (DATE '2009-12-31' - DATE '2009-01-01') / 7)
SELECT RTRIM (
XMLAGG (XMLELEMENT (
e,
friday_date || ','
)).EXTRACT ('//text()'),
COLUMN_VALUE
FROM t2
COLUMN_VALUE
01/02/2009,01/09/2009,01/16/2009,01/23/2009,01/30/2009,02/06/2009,02/13/2009,02/
20/2009,02/27/2009,03/06/2009,03/13/2009,03/20/2009,03/27/2009,04/03/2009,04/10/
2009,04/17/2009,04/24/2009,05/01/2009,05/08/2009,05/15/2009,05/22/2009,05/29/200
9,06/05/2009,06/12/2009,06/19/2009,06/26/2009,07/03/2009,07/10/2009,07/17/2009,0
7/24/2009,07/31/2009,08/07/2009,08/14/2009,08/21/2009,08/28/2009,09/04/2009,09/1
1/2009,09/18/2009,09/25/2009,10/02/2009,10/09/2009,10/16/2009,10/23/2009,10/30/2
009,11/06/2009,11/13/2009,11/20/2009,11/27/2009,12/04/2009,12/11/2009,12/18/2009
,12/25/2009
1 row selected. -
Need ABAP Query Builder Like Ms-SQLQuery Builder for Critical ABAP-Query
Dear ABAP Friends,
I Need ABAP Query Builder which is as flexible as Ms-SQLQuery Builder for building Critical ABAP-Queries e.g. "I have 4 master tables , Each master table having self-join with some condition and these 4 Result-Sets have Innser-Join+Left Outer Join " Please Help.I have seen TCODE SQ01, But I found that this TCODE may be used to build simple ABAP Query with Selection-screen which can be used for generating simple report. But i think for critical query ??????????
I have build my Query in MS-SQL and got the right output, Now how do I write this in ABAP Using Join statement. Please Help.....................
My SQL Query as below(Remember this is a single Query and verified correct in SQL):
SELECT P1.PERNR, P1.ENAME, P1.BEGDA AS P1BEGDA, P1.ENDDA AS P1ENDDA, P1.AEDTM AS P1AEDTM, P1.UNAME AS P1UNAME, P1.PERSG, P1.PERSK,
P1.PLANS,
P2.ENDDA AS P2ENDDA, P2.BEGDA AS P2BEGDA, P2.AEDTM AS P2AEDTM, P2.UNAME AS P2UNAME, P2.GESCH, P2.FAMST,
P21.ENDDA AS P21ENDDA, P21.BEGDA AS P21BEDDA, P21.AEDTM AS P21AEDTM, P21.UNAME AS P21UNAME, P21.FAMSA, P21.FAVOR, P21.FANAM,
P21.FGBDT, P21.FASEX,
P0.ENDDA AS P0ENDDA, P0.BEGDA AS P0BEDDA, P0.AEDTM AS P0AEDTM, P0.UNAME AS P0UNAME, P0.MASSN,
P0.MASSG
FROM (SELECT TOP (100) PERCENT PA0001_2.PERNR, PA0001_2.ENDDA, PA0001_2.BEGDA, PA0001_2.AEDTM, PA0001_2.UNAME, PA0001_2.PERSG,
PA0001_2.PERSK, PA0001_2.PLANS, PA0001_2.ENAME
FROM PA0001 AS PA0001_2 INNER JOIN
(SELECT PERNR, MAX(ENDDA) AS ENDDA
FROM PA0001 AS PA0001_1
GROUP BY PERNR) AS Pi1
ON PA0001_2.PERNR = Pi1.PERNR
AND PA0001_2.ENDDA = Pi1.ENDDA
ORDER BY PA0001_2.PERNR) AS P1 LEFT OUTER JOIN
(SELECT TOP (100) PERCENT PA0000.PERNR, PA0000.ENDDA, PA0000.BEGDA, PA0000.AEDTM, PA0000.UNAME, PA0000.MASSN,
PA0000.MASSG
FROM PA0000 INNER JOIN
(SELECT PERNR, MAX(AEDTM) AS Pi0AEDTM
FROM PA0000 AS PA0000_1
GROUP BY PERNR) AS Pi0 ON PA0000.PERNR = Pi0.PERNR AND PA0000.AEDTM = Pi0.Pi0AEDTM
ORDER BY PA0000.PERNR) AS P0 ON P1.PERNR = P0.PERNR LEFT OUTER JOIN
(SELECT TOP (100) PERCENT PA0021.PERNR, PA0021.ENDDA, PA0021.BEGDA, PA0021.AEDTM, PA0021.UNAME, PA0021.FAMSA, PA0021.FAVOR,
PA0021.FANAM, PA0021.FGBDT, PA0021.FASEX
FROM PA0021 INNER JOIN
(SELECT PERNR, MAX(AEDTM) AS Pi21AEDTM
FROM PA0021 AS PA0021_1
GROUP BY PERNR) AS Pi21 ON PA0021.PERNR = Pi21.PERNR AND PA0021.AEDTM = Pi21.Pi21AEDTM
ORDER BY PA0021.PERNR) AS P21 ON P1.PERNR = P21.PERNR LEFT OUTER JOIN
(SELECT TOP (100) PERCENT PA0002.PERNR, PA0002.ENDDA, PA0002.BEGDA, PA0002.AEDTM, PA0002.UNAME, PA0002.GESCH,
PA0002.FAMST
FROM PA0002 INNER JOIN
(SELECT PERNR, MAX(ENDDA) AS Pi2ENDDA
FROM PA0002 AS PA0002_1
GROUP BY PERNR) AS Pi2 ON PA0002.PERNR = Pi2.PERNR AND PA0002.ENDDA = Pi2.Pi2ENDDA
ORDER BY PA0002.PERNR) AS P2 ON P1.PERNR = P2.PERNR
xxxxx----
Edited by: Goutam Roy on May 5, 2009 1:11 PM -
Hi,
I need a query having the column name with comma...
For Ex.
select table_name from user_tables;
I need the output as
one,
two,
three,
etc...,
Kinldy provide me the query,...
Rgds...
Edited by: user537350 on May 28, 2009 10:20 PMSQL> select abc||',' from wipro;
abc||','
abc,
abc,
abc,
abc, -
I Have some 3 tables for example as below
Order Table :_
Order_ID Order Name
1 Order1
2 Order2
3 Order3
Item Table:_
Item_id Item_name Order_id
100 item1 1
101 item2 1
102 item3 2
201 item4 2
202 item1 3
203 item2 3
Customer table:_
Customer_id Cust_Name Order_id
500 a1 1
501 a2 1
502 a3 2
503 a4 2
504 a5 3
505 a6 3
I need a query to fetch the Order name from the Order tables by giving input as Items and Customer details.
Example: Input as
Case 1:
Items: Item1, Item2
Customers: a1,a2
Result should be Order1
Case 2:
Items : Item1,Item2
Customers: a1,a2,a5,a6
Result should be order1,order3
Use Case:
When both my Items as well as customer are satisfied for a single order , then only those order details has to be displayed else null.983832 wrote:
Sorry I am new to this forumThen I suggest you to start reading: SQL and PL/SQL FAQ
Particularly post CREATE TABLE and INSERT statements, explain the logic and post your expected output.
When you put some code or output please enclose it between two lines starting with {noformat}{noformat}
i.e.:
{noformat}{noformat}
SELECT ...
{noformat}{noformat}
It's also considered a good practice to mark questions as answered when the answers are satisfying your question or provide additional details.
Regards.
Al -
Need a query for monthly Report
Hello All,
I need a query for monthly report,
comp_code
emp_id
dept_id
work_day
100
A100
MECH
01/01/2013
100
A100
MECH
02/01/2013
100
A100
MECH
03/01/2013
100
A100
MECH
04/01/2013
100
A100
MECH
05/02/2013
100
A100
MECH
08/02/2013
100
A100
MECH
09/02/2013
100
A100
MECH
10/02/2013
100
A100
MECH
12/05/2013
100
A100
MECH
13/05/2013
100
A101
CIV
01/04/2013
100
A101
CIV
02/04/2013
100
A101
CIV
03/04/2013
100
A101
CIV
04/04/2013
100
A101
CIV
06/04/2013
100
A101
CIV
06/06/2013
100
A101
CIV
07/06/2013
100
A101
CIV
08/06/2013
100
A101
CIV
09/06/2013
100
A101
CIV
10/06/2013
100
A101
CIV
11/12/2013
100
A101
CIV
12/12/2013
100
A101
CIV
13/12/2013
100
A101
CIV
14/12/2013
Dear friends this the sample table of my report.In which table has contain list of employees with their working days(actual table has contain almost 5laks of records).
suppose user choose the date between 01/01/2013 and 31/12/2013 then the result should be like this.
comp_code
emp_id
dept_id
month
Total_work
100
A100
MECH
JANUARY
4
100
A100
MECH
FEBRUARY
2
100
A100
MECH
MARCH
0
100
A100
MECH
APRIL
0
100
A100
MECH
MAY
2
100
A100
MECH
JUNE
0
100
A100
MECH
JULY
0
100
A100
MECH
AUGUST
0
100
A100
MECH
SEPTEMBER
0
100
A100
MECH
OCTOBER
0
100
A100
MECH
NOVEMBER
0
100
A100
MECH
DECEMBER
0
100
A101
CIV
JANUARY
0
100
A101
CIV
FEBRUARY
0
100
A101
CIV
MARCH
0
100
A101
CIV
APRIL
5
100
A101
CIV
MAY
0
100
A101
CIV
JUNE
5
100
A101
CIV
JULY
0
100
A101
CIV
AUGUST
0
100
A101
CIV
SEPTEMBER
0
100
A101
CIV
OCTOBER
0
100
A101
CIV
NOVEMBER
0
100
A101
CIV
DECEMBER
4Hi,
If you want the output to include months where no work was done (with 0 in the total_work column) then you need to outer-join a "table" that has one row per month, and make it a partitioned outer join:
WITH got_end_points AS
SELECT TRUNC (MIN (work_day), 'MONTH') AS first_month
, TRUNC (MAX (work_day), 'MONTH') AS last_month
FROM table_x
, all_months AS
SELECT ADD_MONTHS (first_month, LEVEL - 1) AS a_month
, ADD_MONTHS (first_month, LEVEL) AS next_month
FROM got_end_points
CONNECT BY LEVEL <= 1 + MONTHS_BETWEEN (last_month, first_month)
SELECT t.comp_code
, t.emp_id
, t.dept_id
, m.a_month
, COUNT (t.work_day) AS total_work
FROM all_months m
LEFT OUTER JOIN table_x t PARTITION BY (t.comp_code, t.emp_id, t.ept_id)
ON t.work_day >= a.a_month
AND t.work_day < a.next_month
GROUP BY t.comp_code
, t.emp_id
, t.dept_id
, m.a_month
ORDER BY t.comp_code
, t.emp_id
, t.dept_id
, m.a_month
As posted, this include every month that is actually in the table. You can change the first sub-query if you want to enter first and last months.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Point out where the query above is giving the wrong results, and explain, using specific examples, how you get the correct results from the given data in those places. If you changed the query at all, post your code.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
Need Sql Query that Suppress the repeating rows.
Hi Sir,
I have below data set.
DeptID Sum(SAL) Avg(Sal)
10 1300 1300
10 2450 1300
10 5000 1300
20 800 800
20 1100 800
20 2975 800
20 3000 800
30 800 800
30 1100 800
30 2975 800
40 3000 800
40 4000 900
I Need SQL query that can remove the duplicate or suppress.Just like below data set.
Output:
DeptID Sum(SAL) Avg(Sal)
10 1300 1300
2450 1300
5000 1300
20 800 800
1100 800
2975 800
3000 800
800 800
30 1100 800
2975 800
40 3000 800
4000 900
Could you please help me on this..Your requiremnt is more of a reporting request which should not be handled in SQL. For example in SQL Plus you can use the BREAK command
SQL> break on deptno
SQL> select deptno, ename from emp order by deptno;
DEPTNO ENAME
10 KING
CLARK
20 JONES
SCOTT
SMITH
ADAMS
30 TURNER
MARTIN
WARD
ALLEN
BLAKE
11 rows selected.
SQL>
But if you still wish to do it in SQL you can use ROW_NUMBER analytic function and achieve it like this
select decode(rno, 1, deptno) deptno
, ename
from (
select row_number() over(partition by deptno order by ename) rno
, deptno
, ename
from emp -
Looking for query for below output?
Hello Experts,
I have couple of master tables and those are linked with my audit table.
For example, below are 2 master tables,
CREATE TABLE MASTER1 (MASTER1_UID INT IDENTITY(1,1) PRIMARY KEY, MASTER1_VAL VARCHAR(10))
INSERT INTO MASTER1 (MASTER1_VAL) VALUES ('VAL1'), ('VAL11'), ('VAL111')
--SELECT * FROM MASTER1
CREATE TABLE MASTER2 (MASTER2_UID INT IDENTITY(1,1) PRIMARY KEY, MASTER2_VAL VARCHAR(10))
INSERT INTO MASTER2 (MASTER2_VAL) VALUES ('VAL2'), ('VAL22'), ('VAL222')
--SELECT * FROM MASTER2
Now, I have a audit table like below,
CREATE TABLE AUDIT(BOOK_ID INT, FIELD_NAME VARCHAR(10), OLD_VAL VARCHAR(10), NEW_VAL VARCHAR(10))
INSERT INTO AUDIT VALUES (10, 'FIELD1', 'TEST-1', 'TEST-2'), (10, 'FIELD2', '1', '2'), (10, 'FIELD3', '1', '2')
--SELECT * FROM AUDIT
Here,
1. "FIELD2" data (1 & 2) linked with "MASTER1" table
2. "FIELD3" data (1 & 2) linked with "MASTER2" table
Now, I need to query on "AUDIT" table JOIN with master tables "MASTER1" & "MASTER2"and need below output,
Note - I having 15 master table and data in audit table with relation with those master tables.
Please suggest some query on this? Thanks!
CREATE TABLE MASTER1 (MASTER1_UID INT IDENTITY(1,1) PRIMARY KEY, MASTER1_VAL VARCHAR(10))
INSERT INTO MASTER1 (MASTER1_VAL) VALUES ('VAL1'), ('VAL11'), ('VAL111')
--SELECT * FROM MASTER1
CREATE TABLE MASTER2 (MASTER2_UID INT IDENTITY(1,1) PRIMARY KEY, MASTER2_VAL VARCHAR(10))
INSERT INTO MASTER2 (MASTER2_VAL) VALUES ('VAL2'), ('VAL22'), ('VAL222')
--SELECT * FROM MASTER2
CREATE TABLE AUDIT(BOOK_ID INT, FIELD_NAME VARCHAR(10), OLD_VAL VARCHAR(10), NEW_VAL VARCHAR(10))
INSERT INTO AUDIT VALUES (10, 'FIELD1', 'TEST-1', 'TEST-2'), (10, 'FIELD2', '1', '2'), (10, 'FIELD3', '1', '2')
--SELECT * FROM AUDIT
--select * from MASTER1
--select * from MASTER2
;with mycte as (
select * from Audit
cross apply (values(Cast(Old_Val as varchar(50))),(Cast(New_Val as varchar(50)))) d(val)
,mycte1 as (
Select BOOK_ID,FIELD_NAME, val, MASTER1_VAL, MASTER2_VAL
, row_number() Over(Partition by FIELD_NAME Order by val ) rn from mycte m0
Left join Master1 m1 on m0.val=Cast(m1.MASTER1_UID as varchar(50)) and m0.Field_NAME='FIELD2'
Left join Master2 m2 on m0.val=Cast(m2.MASTER2_UID as varchar(50) ) and m0.Field_NAME='FIELD3'
Select BOOK_ID, FIELD_NAME, [1] as OLD_VAL,[2] as NEW_VAL from
(Select BOOK_ID,FIELD_NAME, rn,coalesce(MASTER2_VAL, MASTER1_VAL, val) as val from mycte1) src
pivot (max(val) For rn in ([1],[2],[3])) pvt
drop table MASTER1,MASTER2,AUDIT -
I have one table Prd_mst, I need a query or function where whenever i pass the child_id into query or function i get the Parent_id of that
example Data is below :-
P_ID,P_NAME,C_ID
null,Computer,1
1,KeyBoard,2
1,Mouse,3
1,Mother Board,4
3,Scroll Mouse,5
3,Optical Scroll Mouse,6
3,Fibre Scroll Mouse,7
2,Multimedia Key Board,8
2,Cordless Key Board,10
2,Normal Key Board,9
4,586 Mother Board,13
4,386 Mother Board,11
4,486 Mother Board,12
4,P1 Mother Board,14
4,P2 Mother Board,15
4,P3 Mother Board,16
4,P4 Mother Board,17
14,533 Mhtz P1 CPU,19
14,433 Mhtz P1 CPU,18
19,533 Mhtz P1 CPU With 100Mhtz BUS,20
19,533 Mhtz P1 CPU With 133Mhtz BUS,21
18,433 Mhtz P1 CPU With 100Mhtz BUS,22
So when ever i put the child id as 22 i should get the 14
So when ever i put the child id as 21 i should get the 14
So when ever i put the child id as 9 i should get the 1
So when ever i put the child id as 15 i should get the 1
So when ever i put the child id as 5 i should get the 1
So when ever i put the child id as 3 i should get the null
So when ever i put the child id as 14 i should get the 1.
Please help me......
There is one complex requirement in matrix format.
Need P_ID , P_NAME , Count( child records)
P_(nth), P_NAME(nth), Count(child record) nth times.
Child is again the parent of some child.
Report is needed for audit purpose.
Message was edited by: Sandeep Sharma
Sandeep SharmaSQL> CREATE TABLE SANDEEP(P_ID NUMBER,P_NAME VARCHAR2(100),C_ID NUMBER);
Table created.
SQL> INSERT INTO SANDEEP VALUES(null,'Computer',1);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(1,'KeyBoard',2);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(1,'Mouse',3);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(1,'Mother Board',4);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(3,'Scroll Mouse',5);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(3,'Optical Scroll Mouse',6);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(3,'Fibre Scroll Mouse',7);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(2,'Multimedia Key Board',8);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(2,'Cordless Key Board',10);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(2,'Normal Key Board',9);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(4,'586 Mother Board',13);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(4,'386 Mother Board',11);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(4,'486 Mother Board',12);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(4,'P1 Mother Board',14);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(4,'P2 Mother Board',15);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(4,'P3 Mother Board',16);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(4,'P4 Mother Board',17);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(14,'533 Mhtz P1 CPU',19);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(14,'433 Mhtz P1 CPU',18);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(19,'533 Mhtz P1 CPU With 100Mhtz BUS',20);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(19,'533 Mhtz P1 CPU With 133Mhtz BUS',21);
1 row created.
SQL> INSERT INTO SANDEEP VALUES(18,'433 Mhtz P1 CPU With 100Mhtz BUS',22);
1 row created.
SQL> COMMIT;
Commit complete.
SQL> set null null
SQL> SELECT P_ID
2 FROM SANDEEP
3 WHERE LEVEL = 2
4 START WITH C_ID = &1
5 CONNECT BY C_ID = PRIOR P_ID;
Enter value for 1: 22
old 4: START WITH C_ID = &1
new 4: START WITH C_ID = 22
P_ID
14
SQL> /
Enter value for 1: 21
old 4: START WITH C_ID = &1
new 4: START WITH C_ID = 21
P_ID
14
SQL> /
Enter value for 1: 9
old 4: START WITH C_ID = &1
new 4: START WITH C_ID = 9
P_ID
1
SQL> /
Enter value for 1: 15
old 4: START WITH C_ID = &1
new 4: START WITH C_ID = 15
P_ID
1
SQL> /
Enter value for 1: 5
old 4: START WITH C_ID = &1
new 4: START WITH C_ID = 5
P_ID
1
SQL> /
Enter value for 1: 3
old 4: START WITH C_ID = &1
new 4: START WITH C_ID = 3
P_ID
null
SQL> /
Enter value for 1: 14
old 4: START WITH C_ID = &1
new 4: START WITH C_ID = 14
P_ID
1
SQL> SY.
Maybe you are looking for
-
Error while captuirng excise at depot in J1IG
Dear all During excise capture at depot for second line item of invoice it is showing error "Excise invocie has no matching lines" Both items in invoice are of same batch. This problem is occuring whenever we have multi line items in invocie withs am
-
Looking for a "clean" video cable for adding 2nd monitor to 24" iMac. The back of the computer faces the world. Would like to have short 12-18" monitor cable (dreaming) and not have to use Apples adapter attached to 6' folded up vga video cable. And
-
Picture Messages Pix-Flix ect Not Showing In Usage Anymore
A few days ago I noticed that none of the picture messages were showing up in that category on the usage page on my Verizon anyone know why?
-
Hi If i Route Traffice from External to internal . Why TMG is automaticaly routing Traffic from Internal to External. Is to some issues with configuration ?
-
Hi experts, I would like to have the TAB key blocked for certain fields in documents. The reason for this is that I want to filter permanently, for example, the customer list for the Sales Order. My idea is to create a FMS query and link this field t