HANA SQL - Create multiple rows from one row based on calculation - hana

I have the following 2 records:
Batch
Qty
QtyPer
PackNum
One
60
20
3
Two
20
10
2
I need to find a way to create multiple rows based on Qty/PackNum, such as:
Batch
Qty
QtyPer
PackNum
Level
One
60
20
3
1
One
60
20
3
2
One
60
20
3
3
Two
20
10
2
1
Two
20
10
2
2
I've tried using the WITH command to no avail.
Any Ideas?
Marcus

one alternate is construct as dummy table or dummy sql with below structure and do the cross join on the pack_number. You could also try sql procedure with global/local temporary table
pack number, level
3,1
3,2
3,3
2,1
2,2
or
below is the pseudo sql
select it.*,dd.level from(
select 3 as pack_number , 1 as level from dummy
union all
select 3 as pack_number , 2 as level from dummy
union all
select 3 as pack_number , 3 as level from dummy
union all
select 2 as pack_number , 1 as level from dummy
union all
select 2 as pack_number , 2 as level from dummy
....
) as dummy_data as dd
inner join
input_tab as it
on dd. pack_number = it.pack_number

Related

SQL How to SUM rows in second column if first column contain

View of a table
ID
kWh
1
3
1
10
1
8
1
11
2
12
2
4
2
7
2
8
3
3
3
4
3
5
I want to recive
ID
kWh
1
32
2
31
3
12
The table itself is more complex and larger. But the point is this. How can this be done? And I can't know in advance the ID numbers of the first column.
SELECT T.ID,SUM(T.KWH)SUM_KWH
FROM YOUR_TABLE T
GROUP BY T.ID
Do you need this one?
Let's assume your database name is 'testdb' and table name is 'table1'.
SELECT * FROM testdb.table1;
SELECT id, SUM(kwh) AS "kwh2"
FROM stack.table1
WHERE id = 1
keep running the query will all (ids). you will get output.
By following this query you will get desired output.
Hope this helps.

Populate a numbered row until reaching a specific value with another column

I have a table full of account numbers and period/terms for loan(loan term is in months)
What I need to do is populate a numbered row for each account number that is less than or equal to the loan term. I've attached a screen shot below:
Example
So for this specific example, I will need 48 numbered rows for this account number, as the term is only 48 months.
Thanks for the help!
with
test_data ( account_nmbr, term ) as (
select 'ABC200', 6 from dual union all
select 'DEF100', 8 from dual
)
-- End of simulated inputs (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select level as row_nmbr, term, account_nmbr
from test_data
connect by level <= term
and prior account_nmbr = account_nmbr
and prior sys_guid() is not null
order by account_nmbr, row_nmbr -- If needed
;
ROW_NMBR TERM ACCOUNT_NMBR
-------- ---------- ------------
1 6 ABC200
2 6 ABC200
3 6 ABC200
4 6 ABC200
5 6 ABC200
6 6 ABC200
1 8 DEF100
2 8 DEF100
3 8 DEF100
4 8 DEF100
5 8 DEF100
6 8 DEF100
7 8 DEF100
8 8 DEF100
In Oracle 12, you can use the LATERAL clause for the same:
with
test_data ( account_nmbr, term ) as (
select 'ABC200', 6 from dual union all
select 'DEF100', 8 from dual
)
-- End of simulated inputs (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select l.row_nmbr, t.term, t.account_nmbr
from test_data t,
lateral (select level as row_nmbr from dual connect by level <= term) l
order by account_nmbr, row_nmbr -- If needed
;

Select to build groups by (analytic) sum

Please help me to build a sql select to assign (software development) tasks to a software release. Actually this is a fictive example to solve my real business specific problem.
I have a relation Tasks:
ID Effort_In_Days
3 3
1 2
6 2
2 1
4 1
5 1
I want to distribute the Tasks to releases which are at most 2 days long (tasks longer than 2 shall still be put into one release). In my real problem I have much more "days" available to distribute "tasks" to. Expected output:
Release Task_ID
1 3
2 1
3 6
4 2
4 4
5 5
I think I need to use analytic functions, something with sum(effort_in_days) over and so on, to get the result. But I'm I haven't used analytic functions much and didn't find an example that's close enough to my specific problem. I need to build groups (releases) if a sum (>= 2) is reached.
I would do something like:
with data as (
select 3 ID, 3 Effort_In_Days from dual union all
select 1 ID, 2 Effort_In_Days from dual union all
select 6 ID, 2 Effort_In_Days from dual union all
select 2 ID, 1 Effort_In_Days from dual union all
select 4 ID, 1 Effort_In_Days from dual union all
select 5 ID, 1 Effort_In_Days from dual
)
select id, effort_in_days, tmp, ceil(tmp/2) release
from (
select id, effort_in_days, sum(least(effort_in_days, 2)) over (order by effort_in_days desc rows unbounded preceding) tmp
from data
);
Which results in:
ID EFFORT_IN_DAYS TMP RELEASE
---------- -------------- ---------- ----------
3 3 2 1
1 2 4 2
6 2 6 3
2 1 7 4
4 1 8 4
5 1 9 5
Basically, I am using least() to convert everything over 2 down to 2. Then I am putting all rows in descending order by that value and starting to assign releases. Since they are in descending order with a max value of 2, I know I need to assign a new release every time when I get to a multiple of 2.
Note that if you had fractional values, you could end up with releases that do not have a full 2 days assigned (as opposed to having over 2 days assigned), which may or may not meet your needs.
Also note that I am only showing all columns in my output to make it easier to see what the code is actually doing.
This is an example of a bin-packing problem (see here). There is not an optimal solution in SQL, that I am aware of, except in some boundary cases. For instance, if all the tasks have the same length or if all the tasks are >= 2, then there is an easy-to-find optimal solution.
A greedy algorithm works pretty well. This is to put a given record in the first bin where it fits, probably going through the list in descending size order.
If your problem is really as you state it, then the greedy algorithm will work to produce an optimal solution. That is, if the maximum value is 2 and the efforts are integers. There might even be a way to calculate the solution in SQL in this case.
Otherwise, you will need pl/sql code to achieve an approximate solution.
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE data AS
select 3 ID, 3 Effort_In_Days from dual union all
select 1 ID, 2 Effort_In_Days from dual union all
select 6 ID, 2 Effort_In_Days from dual union all
select 2 ID, 1 Effort_In_Days from dual union all
select 4 ID, 1 Effort_In_Days from dual union all
select 5 ID, 1 Effort_In_Days from dual union all
select 9 ID, 2 Effort_In_Days from dual union all
select 7 ID, 1 Effort_In_Days from dual union all
select 8 ID, 1 Effort_In_Days from dual;
Query 1:
Give the rows an index so that they can be kept in order easily;
Assign groups to the rows where the Effort_In_Days is 1 so that all adjacent rows with Effort_In_Days of 1 are in the same group and rows separated by higher values for Effort_In_Days are in different groups;
Assign a cost of 1 to each row where the Effort_In_Days is higher than 1 or where Effort_In_Days is 1 and the row has an odd row number within the group; then
Finally, the release is the sum of all the costs for the row and all preceding rows.
Like this:
WITH indexes AS (
SELECT ID,
Effort_In_Days,
ROWNUM AS idx
FROM Data
),
groups AS (
SELECT ID,
Effort_In_Days,
idx,
CASE Effort_In_Days
WHEN 1
THEN idx - ROW_NUMBER() OVER ( PARTITION BY Effort_In_Days ORDER BY idx )
END AS grp
FROM indexes
ORDER BY idx
),
costs AS (
SELECT ID,
Effort_In_Days,
idx,
CASE Effort_In_Days
WHEN 1
THEN MOD( ROW_NUMBER() OVER ( PARTITION BY grp ORDER BY idx ), 2 )
ELSE 1
END AS cost
FROM groups
ORDER BY idx
)
SELECT ID,
Effort_In_Days,
SUM( cost ) OVER ( ORDER BY idx ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS Release
FROM costs
ORDER BY idx
Results:
| ID | EFFORT_IN_DAYS | RELEASE |
|----|----------------|---------|
| 3 | 3 | 1 |
| 1 | 2 | 2 |
| 6 | 2 | 3 |
| 2 | 1 | 4 |
| 4 | 1 | 4 |
| 5 | 1 | 5 |
| 9 | 2 | 6 |
| 7 | 1 | 7 |
| 8 | 1 | 7 |

how to generate consecutive records with a given number?

in oracle, is there a built-in function to produce consecutive records with a given number? For example, the number is 100, so that you can generate a result-set with 100 records whose values are 1, 2, 3, 4...100, like the following:
1
2
3
4
...
100
I know store procedure can do this, and I want to know if there are other ways just using sql statements?
select level
from dual
connect by level <= 100
Here is another approach, using model clause. (Oracle 10g and higher).
SQL> select x
2 from dual
3 model
4 dimension by (0 as z)
5 measures (0 as x)
6 rules iterate(101) (
7 x[iteration_number] = iteration_number
8 )
9 ;
X
----------
0
1
2
3
4
5
6
7
8
9
10
11
...
100
Please try using CTE:
WITH numbers(n) AS
(
SELECT 1 FROM dual
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 100
)
SELECT * FROM numbers;
It's traditional to use a hierarchical query:
select level
from dual
connect by level <= 100

Why does CONNECT BY LEVEL on a table return extra rows?

Using CONNECT BY LEVEL seems to return too many rows when performed on a table. What is the logic behind what's happening?
Assuming the following table:
create table a ( id number );
insert into a values (1);
insert into a values (2);
insert into a values (3);
This query returns 12 rows (SQL Fiddle).
select id, level as lvl
from a
connect by level <= 2
order by id, level
One row for each in table A with the value of column LVL being 1 and three for each in table A where the column LVL is 2, i.e.:
ID | LVL
---+-----
1 | 1
1 | 2
1 | 2
1 | 2
2 | 1
2 | 2
2 | 2
2 | 2
3 | 1
3 | 2
3 | 2
3 | 2
It is equivalent to this query, which returns the same results.
select id, level as lvl
from dual
cross join a
connect by level <= 2
order by id, level
I don't understand why these queries return 12 rows or why there are three rows where LVL is 2 and only one where LVL is 1 for each value of the ID column.
Increasing the number of levels that are "connected" to 3 returns 13 rows for each value of ID. 1 where LVL is 1, 3 where LVL is 2 and 9 where LVL is 3. This seems to suggest that the rows returned are the number of rows in table A to the power of the value of LVL minus 1.
I would have though that these queries would be the same as the following, which returns
6 rows
select id, lvl
from ( select level as lvl
from dual
connect by level <= 2
)
cross join a
order by id, lvl
The documentation isn't particularly clear, to me, in explaining what should occur. What's happening with these powers and why aren't the first two queries the same as the third?
When connect by is used without start with clause and prior operator, there is no restriction on joining children row to a parent row. And what Oracle does in this situation, it returns all possible hierarchy permutations by connecting a row to every row of level higher.
SQL> select b
2 , level as lvl
3 , sys_connect_by_path(b, '->') as ph
4 from a
5 connect by level <= 2
6 ;
B LVL PH
---------- ----------
1 1 ->1
1 2 ->1->1
2 2 ->1->2
3 2 ->1->3
2 1 ->2
1 2 ->2->1
2 2 ->2->2
3 2 ->2->3
3 1 ->3
1 2 ->3->1
2 2 ->3->2
3 2 ->3->3
12 rows selected
In the first query, you connect by just the level.
So if level <= 1, you get each of the records 1 time. If level <= 2, then you get each level 1 time (for level 1) + N times (where N is the number of records in the table). It is like you are cross joining, because you're just picking all records from the table until the level is reached, without having other conditions to limit the result. For level <= 3, this is done again for each of those results.
So for 3 records:
Lvl 1: 3 record (all having level 1)
Lvl 2: 3 records having level 1 + 3*3 records having level 2 = 12
Lvl 3: 3 + 3*3 + 3*3*3 = 39 (indeed, 13 records each).
Lvl 4: starting to see a pattern? :)
It's not really a cross join. A cross join would only return those records that have level 2 in this query result, while with this connect by, you get the records having level 1 as well as the records having level 2, thus resulting in 3 + 3*3 instead of just 3*3 record.
you're comparing apples to oranges when comparing the final query to the others as the LEVEL is isolated in that to the 1-row dual table.
lets consider this query:
select id, level as lvl
from a
connect by level <= 2
order by id, level
what that is saying is, start with the table set (select * From a). then, for each row returned connect this row to the prior row. as you have not defined a join in the connect by, this is in effect a Cartesian join, so when you have 3 rows of (1,2,3) 1 joins to 2, 1->3, 2->1, 2->3, 3->1 and 3->2 and they also join to themselves 1->1,2->2 and 3->3. these joins are level=2. so we have 9 joins there, which is why you get 12 rows (3 original "level 1" rows plus the Cartesian set).
so the number of rows output = rowcount + (rowcount^2)
in the last query you are isolating level to this
select level as lvl
from dual
connect by level <= 2
which of course returns 2 rows. this is then cartesianed to the original 3 rows, giving 6 rows as output.
You can use technique below to overcome this issue:
select id, level as lvl
from a
left outer join (select level l from dual connect by level <= 2) lev on 1 = 1
order by id