How to repeat rows based on column value
Hi all,
I have a query that gives me a result with a column value for example 4.
I now want to repeat this row 4 times with a new column that calculated from 1 - 4.
Or when column value is 3 I want to repeat row 3 times with new column name 1-3
Can anyone help me with this please? :)
Hi Yvanlathem,
To achieve your requirement, you can reference the recursive approach as below.
DECLARE @T TABLE(Col1 CHAR(1),Col2 INT)
INSERT INTO @T VALUES('A',1),('B',2),('C',3)
;WITH Cte([Char],[Repeat]) AS
SELECT Col1,Col2 FROM @T
UNION ALL
SELECT [Char],[Repeat]-1 FROM Cte
WHERE [Repeat]>1
SELECT * FROM Cte ORDER BY [Char],[Repeat]
OPTION(MAXRECURSION 0)
/* Output
Char Repeat
A 1
B 1
B 2
C 1
C 2
C 3
If you have any question, feel free to let me know.
Eric Zhang
TechNet Community Support
Similar Messages
-
Combine rows based on column value
I'm trying to combine rows based off of a common value.
Table Data:
Result A
Player_ID Player_Name Team_Name Points Sequence
99999 John Smith Bulls 50 1
99999 John Smith Pistons 14 2
What i want in the output
Result B
Player_ID Player_Name Team_Name Points
99999 John Smith Bulls 64 (50 for Bulls)Here's my main query...
select player_id, player_name, team_name, points
from
SELECT player_id, player_name, team_name, sum(points) sum_points
FROM stats_data
WHERE season_id = 2008
AND points > 0
GROUP BY player_id, player_name, team_name
) t
ORDER BY sum_points DESC, last_name;**The current query gives me the output from Result A
1) Not entirely sure how to combine data based of player_id
2) Once i figure out 1, im sure by adding the ('sum_points' for 'team_name') to the output can be done with a case statement, i think?Sorry about that Frank.
Using: Oracle 10.2g
i was incorrect about the output of the query
SELECT player_id, sum(points) sum_points
FROM stats_data
WHERE season_id = 2008
AND points > 0
GROUP BY player_id
)Output
Player_ID Sum_Points
99999 20
55455 6
66489 2 So the subquery is outputing the correct data
The output of the original entire query(that you had posted) is:
Player_ID Player_Name Team_Name Points
99999 John Smith Bulls 16 (8 for Bulls)
55455 Bob Johnson Rockets 6 (3 for Rockets)
66489 Chris Terry Kings 2 (1 Kings)Here's some more raw sample data from the table:
Player_ID Player_Name Team_Name Points Sequence Game_Type_ID Team_ID
99999 John Smith Bulls 12 1 1 5
99999 John Smith Bulls 0 1 -1 5
99999 John Smith Pistons 4 2 1 12
99999 John Smith Pistons 0 2 -1 12
55455 Bob Johnson Rockets 4 1 1 3
55455 Bob Johnson Rockets 0 1 -1 3
66489 Chris Terry Kings 2 1 1 8
66489 Chris Terry Kings 0 1 -1 8So your code frank is very close, the issue is that:
A) All players have a ('pt value' for 'team name') even if they played on the same team, which can prob. be solved with a case statement, which i tried to do in my last post.
WITH grouped_data AS
SELECT player_id, sum(points) sum_points
FROM stats_data
WHERE season_id = 2008
AND points > 0
GROUP BY player_id
SELECT g.player_id
, s.player_name
, s.team_name
(case when sequence = 2 then g.sum_points <==
|| '('
|| TO_CHAR (s.points)
|| ' for '
|| s.team_name
|| ')'
else to_char (g.sum_points)
END) AS points
FROM grouped_data g
JOIN stats_data s ON g.player_id = s.player_id
WHERE s.sequence in (1,2) <==
AND s.season_id = 2008
AND s.points > 0;the output has two issues, for players who played on more than one team, like Josh Smith the output comes out as
99999 John Smith Pistons 20 (2 for Pistons)
99999 John Smith Bulls 20While the players who played on one team came out correctly. So issue with my edit of your code is:
A) josh smith is output 2, needs to be output once
B)josh smith should say (Josh Smith Bulls 20 (4 for Pistons) not "99999 John Smith Pistons 20 (2 for Pistons)"
c) Issues with "99999 John Smith Pistons 20 (2 for Pistons)" is that it listing the wrong team for him: should be Bulls and listing half of his total with the pistons in the prentices should be 4. --The reason that is because s.points needs to be summed as based off of the data there's two entries
Hope this clears it up, thanks!
Edited by: user652714 on Mar 11, 2009 9:28 AM -
How to identfy rows with same column value
Hi
I have a table student
id ( pkey)
name
class
marks
i need to check the existence of duplicate values like
say the values are :
id name class marks
1 alan 6 85
2 victor 4 97
3 alan 6 85
i need to know if there is any matching row in the table --- like in this case id=1 and id=3 have same value for all the columns except for id .
so the result shud tell me the ids which have duplicate values for name , class , marks and also those ids for which there is no duplicacy
for id= 1 i see that id= 3 has same values
and id=2 has no duplicates
how do i show it ??
The result i expect is
name class marks count
alan 6 85 2
victor 4 97 1
Message was edited by:
SHUBHEMP
id name class marks
1 alan 6 85
2 victor 4 97
3 alan 6 85
You can use a self join to pull out the data which are almost duplicate without a column values here in this example without id the first and third records are duplicate.
select e.id,e.name,e.class,e.marks from EMP e,EMP d where e.name=d.ename and e.class=d.class and e.marks=d.marks and e.id<>d.id; -
Insert rows based on column value
I have customer_ no., Date and no_months as columns. I need to insert in a new table the customer_no as many times as the value of no_months column. Meaning if customer_no is 001 and if months value is 3 then in the new table I want three rows having customer_no as 001 and the date. Any help is highly appreciated.
Something like this?
SQL> with t
2 as
3 (select 23 cust_no,3 mon from dual
4 union all
5 select 10,9 from dual
6 union all
7 select 5,12 from dual
8 union all
9 select 7,1 from dual
10 )
11 select cust_no,mon
12 from
13 (
14 select cust_no,mon,row_number() over(partition by cust_no order by cust_no) rn from t,dba_tables
15 )
16 where rn<=mon
17 /
CUST_NO MON
5 12
5 12
5 12
5 12
5 12
5 12
5 12
5 12
5 12
5 12
5 12
CUST_NO MON
5 12
7 1
10 9
10 9
10 9
10 9
10 9
10 9
10 9
10 9
10 9
CUST_NO MON
23 3
23 3
23 3
25 rows selected.
SQL> -
How to select rows with duplicate column values
hi,
i have a table property_details which has these 2 columns customerno and propertyno a customer can have many properties and property number has to be unique. but somehow these property number has been duplicated at an earlier stage so i have for a customer with many properties the same property number
how i will select such records whose asset numbers are the same
for ex
customer no property no
a1300 1
a1300 1
a1300 1
a2330 10
a2330 10
a2330 10
kindly suggest me a solutionthis example might be of help.
SQL> select * from employees;
YEAR EM NAME PO
2001 02 Scott 91
2001 02 Scott 01
2001 02 Scott 07
2001 03 Tom 81
2001 03 Tom 84
2001 03 Tom 87
6 rows selected.
SQL> select year, empcode, name, position,
2 row_number() over (partition by year, empcode, name
3 order by year, empcode, name, position) as rn
4 from employees;
YEAR EM NAME PO RN
2001 02 Scott 01 1
2001 02 Scott 07 2
2001 02 Scott 91 3
2001 03 Tom 81 1
2001 03 Tom 84 2
2001 03 Tom 87 3
6 rows selected.
SQL> Select year, empcode, name, position
2 From (Select year, empcode, name, position,
3 row_number() over (partition by year, empcode, name
4 order by year, empcode, name, position) as rn
5 From employees) emp
6 Where rn = 1;
YEAR EM NAME PO
2001 02 Scott 01
2001 03 Tom 81
SQL> -
How to get fourthly row (row4) first column value (col1) in matrix
Hi to all,
In FMS, how to get fourthly row (row4) first column value (col1) in matrix in document.
select $[$38.1.4]
But it display the first row
Please give me hint.
Thank youHi Eric,
FMS may only apply to current row. There is no way to get any other fixed row.
Thanks,
Gordon -
Change the row colors based on column values in MOSS 2007.
Hi Team,
I am using MOSS 2007 environment. In that I am having one SharePoint list. In that list based on column values rows colors need to change.
Kindly help me anyone on this.
Thanks,
AshokHi Ashok,
Please follow the below link:
http://www.contentmaster.com/sharepoint-2010/conditional-formatting-of-list-views-for-sharepoint-2010-changing-the-font-colour/
http://sharepoint.stackexchange.com/questions/7478/highlight-row-color-based-on-field-values-in-sharepoint-2010-list-view
Best Regards,
Brij K -
Count the number of rows based on the values!!!
Hi all,
What I am using:
I am working with a multidimensional database in Visual Studio 2010 using its Data source view and calculation member and dimension usage.
What I want to do:
I have a fact table that has five columns(leg(s),hand(s), Head and body,overall) that shows the category of how severe the injury is. Let say for the records all columns never have an empty value(no injury is stated with 'No injury' ) . These five columns
are connected with a dimension that has all the available values (Category A-E of injury).The overall has the most severe from the other four columns. I want to create a bar chart with five different measure
values, one for each column, and count the values in those columns.
For example : I have a slicer in the excel and a bar chart and the slicer has all the values of the Category of the injury ( Cat a,Cat B, Cat C, ... Cat E, No injury ) and when i select one of them, lets say
Cat C, the bar chart should update and show how many Cat C each measurement column has.
Example FACT table:
ID LEG HAND HEAD BODY OVERALL
1 No A No No A
2 No D C C C
3 E C D A A
4 E E B C B
So if i selected C the bar chart will count (Leg = 0, Hand = 1, Head = 1, body = 2 and Overall = 1).
Any ideas ?
Thanks for the help and the time :)Hi DBtheoN,
According to your description, you want to create a chart on excel worksheet to count the rows based on the value, right? If in this case, I am afraid this issue is related to Office forum, I am not the expert of Office, you can post the issue on the corresponding
forum.
However, this requirement can be done easily on SQL Server Reporting Services. You can using the expression below to count the rows.
=COUNT(IIF(Fields!LEG.Value=Parameters!TYPE.Value,1,NOTHING))
Regards,
Charlie Liao
TechNet Community Support -
Color report rows based on a value in that row
I would like to Color report rows based on a value in that row.
For examplle with the "EMP" table:
I would like job=MANAGER to be red and job=CLERK to be green etc etc
The other example I found only had the option of one color either the highlight or the default color.
I am looking for a way to do multiple colors.Hi,
In the row template, you can use #1#, #2#, etc to indicate where a field in the report needs to be output. This does not have to be plain text - ie, you can use it within style tags if you like.
So, take a query like:
SELECT EMPNO,
ENAME,
DEPTNO,
DECODE(DEPTNO, 10, 'green', 20, 'red', 30, 'cyan', 'white') BG_COLOUR
FROM EMPYou get columns 1=empno, 2=ename, 3=deptno and 4=bg_colour. In the row template, you can then do:
Before Rows setting (sets up the table):
<table>
<tr><td>ID</td><td>Name</td><td>Dept</td></tr>After Rows setting (closes the table):
</table>Row Template 1 (used for ALL rows):
<tr style="background-color:#4#;"><td>#1#</td><td>#2#</td><td>#3#</td></tr>Then, for every row, the colour that has been calculated using the DECODE function will be used in the style tag to colour the background for the entire row.
How you determine the colours is up to you. I've used DECODE here, but you could use a field on the DEPT table to hold this and use this in your SQL statement.
Andy -
How to dynamic select based on runtime value ?
how to dynamic select based on runtime value ?
I want to write a select function, which do selecting based on parameters. eg,
CREATE OR REPLACE FUNCTION myfunction
(tableName VARCHAR2, pkName VARCHAR2, pkValue VARCHAR2, requestString VARCHAR2)
RETURN VARCHAR2 AS
BEGIN
select requestString from tableName where pkName=pkValue;
RETURN NULL;
END;
myfunction('users', 'user_id', '100', 'user_name'); it will select 'user_name' from table 'users' where 'user_id' = '100'.
This way could save lots of coding. but it can't pass compiler. how to work out ?
Thanks.While this may save code, if used frequently it will be ineffecient as all [explicative deleted]. The danger is that it would be used even for repeatable statements.
This mode of operation ensures that every statement [calling the funciton] needs to be reparsed, which is extremely expensive in Oracle (in CPU cycles, recursive SQL and shared pool memory).
Such reparsing is rarely a good thing for the environment ... it could easily lead to buying more CPU (bigger box) and therefore adding more Oracle license ... which could quickly exceed the typical developer's salary.
However - if you really, really want to do this, look up 'execute immendiate' in the PL/SQL manuals. -
Performance operations based on Column values in SQL server 2008
Hi ,
I have a table which consist of following columns
ID Formula
Values
DisplayValue
1
a*b/100 100*12/100
null
2
b*c/100
12*4/100
null
I want to perform operation based on column "Values" and save data after operations in new column Name "Display Value" .i.e I want to get the below result . Can anyone please help.
ID Formula
Values
DisplayValue
1
a*b/100 100*12/100
12
2
b*c/100
12*4/100
0.48
Thanks for the help.
Regards, Priti ATry this,
create table #mytable (ID int,Formula varchar(10), [Values] varchar(10), DisplayValue decimal(10,4))
insert into #mytable values(1 ,'a*b/100','100*12/100',null)
insert into #mytable values(2 ,'b*c/100','12*4/100',null)
declare @rowcount int=1
while @rowcount <= (select max(id) from #mytable)
begin
declare @expression nvarchar(max)
select @expression=[values] from #mytable where id = + @rowcount
declare @sql nvarchar(max)
set @sql = 'select @result = ' + @expression
declare @result decimal(10,4)
exec sp_executesql @sql, N'@result decimal(10,4) output', @result = @result out
update #mytable set DisplayValue= @result where id = @rowcount
set @rowcount=@rowcount+1
end
select * from #mytable
Regards, RSingh -
How to repeat row header in all pages in Financial Reporting?
Hi,
I have created a simple Financial Report with landscape mode, I could not able to view the row header in second page. Please help me out , how to repeat row header in all pages?
Edited by: Awesome on Dec 13, 2012 2:04 PMHi,
Refer following link which states how to change the Page Setup setting (just an addition to above poster's explanation):-
http://docs.oracle.com/cd/E12825_01/epm.111/fr_user/frameset.htm?1900.html
Regards,
Edited by: 918547 on Dec 14, 2012 6:17 PM -
How to repeat rows in numbers on every page
how to repeat rows in numbers on every page
Hi mitesh hirani,
Welcome to Apple Support Communities.
Do you mean repeat Header Rows for tables?
Menu > Print... > Print Setup (the panel on the right) > Repeat Table Headers
Regards,
Ian. -
Hello Everyone,
How to update zero to a column value when record does not exist in table but should display the column value when it exists in table
Regards
Regards Gautam SAs per my understanding...
You Would like to see this
Code:
SELECT COALESCE(Salary,0) from Employee;
Regards
Shivaprasad S
Please mark as answer if helpful
Shiv -
How to select 2column from 1 column values
Hi All,
How to select 2column from 1 column values
Ex : In Emp they have JOB column
JOB
CLERK
MANAGER
SALESMAN
MANAGER
MANAGER
ANALYST
PRESIDENT
SALESMAN
CLERK
CLERK
ANALYST
CLERK
here i want to get output like as follows
Ex: ejob1 ejob2
ANALYST SALESMAN
ANALYST SALESMAN
Can anyone helps me in this,it is urget
Thanks,Something like
select a.job, b.job from scott.emp a, (select job from scott.emp) b
CLERK CLERK
CLERK SALESMAN
CLERK SALESMAN
CLERK MANAGER
CLERK SALESMAN
CLERK MANAGER
CLERK MANAGER
CLERK ANALYST
CLERK PRESIDENT
CLERK SALESMAN
CLERK CLERK
CLERK CLERK
CLERK ANALYST
CLERK CLERK
SALESMAN CLERK
SALESMAN SALESMAN
SALESMAN SALESMAN
SALESMAN MANAGER
...
Maybe you are looking for
-
How can i delete my itunes account?
my account has been have like glitches saying that when i purchase something that my Apple ID has not been verified and stuff like that. So i haven't been able to update my Ipod or any apps for the past 4 months or so. I've tried making new accounts
-
HP2540 can no longer be contacted wirelessly. (SOLVED)
Having installed the printer under Linux using CUPS 1.4. I used the Wireless Direct connection to connect to it via my browser and http://192.168.223.1 and set the security to off as we have no neighbours and the router too is unsecured. The printer
-
Etrecheck report....my mac is running so slow. Help!
My mac has been running so slow, and I get lots of spinning balls. Can someone help me fix the issues in this report? Problem description: slow mac EtreCheck version: 2.1.8 (121) Report generated February 18, 2015 at 8:36:21 AM EST Download EtreCheck
-
Match songs appear with wrong information; album art
Two days ago I paid for iTunes match, and uploaded everything from my Laptop library (it has about 98% of my songs available). Today, when go into iTunes on my workstation at work, not only does the song information not match the song, but the album
-
I still can't see my RAW files. Please help!!!