on 2024 Feb 01 9:03 AM
Is there a way to multiply the number of rows returned of a select statement by means of the value of some column?
I have such a case:
create or replace table mytable(OrderName varchar(10), DeliveryAddress varchar(100), NrOfPackets int); insert into mytable values ('OrderA', 'AddressA', 1), ('OrderB', 'AddressB', 2), ('OrderC', 'AddressC', 1);
What I want is to have 2X of the second line (OrderB).
The only helpful solution was using union all like this:
select OrderName, DeliveryAddress from mytable where NrOfPackets > 0 union all select OrderName, DeliveryAddress from mytable where NrOfPackets > 1 order by DeliveryAddress
Is there a better way (without limiting the NrOfPackets)?
Request clarification before answering.
What about a join to the row_generator procedure?
select OrderName, DeliveryAddress from mytable join sa_rowgenerator(0,100) on row_num between 1 and NrOfPackets;
Assumes that NrOfPackets <= 100
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
or safer:
select OrderName, DeliveryAddress from mytable join sa_rowgenerator(1,(select max(NrOfPackets) from mytable)) on row_num <= NrOfPackets order by OrderName;
I got a bit obsessive about this - and I asked ChatGPT It suggested another approach using recursive queries which I don't often use:
WITH RECURSIVE multiplied_rows (OrderName, DeliveryAddress, NrOfPackets) AS (
SELECT OrderName, DeliveryAddress, NrOfPackets
FROM mytable
WHERE NrOfPackets > 0
UNION ALL
SELECT OrderName, DeliveryAddress, NrOfPackets - 1
FROM multiplied_rows
WHERE NrOfPackets > 1
)
SELECT OrderName, DeliveryAddress
FROM multiplied_rows
ORDER BY DeliveryAddress;
which also seems to work.
and then I got really carried away and asked it to illustrate the query!
It came back with this which it described as: Here's an image inspired by the SQL statement you provided, capturing the essence of selecting order names and delivery addresses, combined with the creative process of handling data and organizing it for delivery. This whimsical scene, set in an old-fashioned office bustling with activity, brings the structured query into a vivid, imaginative world.
Ah, that's the new graphical plan analyzer, nice!
That being said, I'm sure the SQL Anywhere-specific row generator procedure and the ability to use that procedure in a FROM clause are waaayyy more efficient and understandable here... - but what do I know 🙂
User | Count |
---|---|
75 | |
30 | |
9 | |
7 | |
7 | |
6 | |
6 | |
5 | |
5 | |
5 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.