-2

There is two table in database.

== tblOrder ==
OrderId
Customer
== tblOrderItem ==
OrderItemId
OrderId
ItemId
Qty
Price

My Query :-

SELECT o.OrderId,o.Customer,oi.ItemId,oi.Qty,oi.Price 
FROM tblorder o
JOIN tblorderitem oi ON oi.OrderId=o.OrderId

Result :-

+---------+----------+--------+-----+-------+
| OrderId | Customer | ItemId | Qty | Price |
+---------+----------+--------+-----+-------+
|    1001 | john day |    501 |   1 |    10 |
|    1001 | john day |    502 |   2 |     9 |
|    1002 | amy gill |    201 |   5 |     2 |
|    1003 | hardcaur |    501 |   1 |    10 |
|    1003 | hardcaur |    509 |   2 |     5 |
|    1003 | hardcaur |    201 |   2 |     2 |
+---------+----------+--------+-----+-------+

I want to generate SNO and SNOI(Temp Serial No) in select statement so that result will be like this :-

+------+---------+----------+------+--------+-----+-------+
| SNO  | OrderId | Customer | SNOI | ItemId | Qty | Price |
+------+---------+----------+------+--------+-----+-------+
|    1 |    1001 | john day |    1 |    501 |   1 |    10 |
|    1 |    1001 | john day |    2 |    502 |   2 |     9 |
|    2 |    1002 | amy gill |    1 |    201 |   5 |     2 |
|    3 |    1003 | hardcaur |    1 |    501 |   1 |    10 |
|    3 |    1003 | hardcaur |    2 |    509 |   2 |     5 |
|    3 |    1003 | hardcaur |    3 |    201 |   2 |     2 |

What will be my query?

Sandeep Tawaniya
  • 717
  • 8
  • 16

1 Answers1

1

You can use variables.

 set @ord ='';
 set @val1 =1;
 set @val2 =0;

select SR_No_1, OrderId, Customer, SR_No_2, ItemId, Qty, Price
from 
(
SELECT    t.*,
          @val1 := if(@ord=OrderId, @val1+1, 1) as SR_No_2,
          @val2 := if(@ord=OrderId,@val2, @val2+1) as SR_No_1,
          @ord := OrderId
FROM      table1 t
 ) t   
ORDER BY  orderId asc;

Result:

+---------+---------+----------+---------+--------+-----+-------+
| SR_No_1 | OrderId | Customer | SR_No_2 | ItemId | Qty | Price |
+---------+---------+----------+---------+--------+-----+-------+
|       1 |    1001 | john day |       1 |    501 |   1 |    10 |
|       1 |    1001 | john day |       2 |    502 |   2 |     9 |
|       2 |    1002 | amy gill |       1 |    201 |   5 |     2 |
|       3 |    1003 | hardcaur |       1 |    501 |   1 |    10 |
|       3 |    1003 | hardcaur |       2 |    509 |   2 |     5 |
|       3 |    1003 | hardcaur |       3 |    201 |   2 |     2 |
+---------+---------+----------+---------+--------+-----+-------+

DEMO

P.S. Kindly note that for demonstration purpose i have inserted data to one table. you can modify the query by introducing the join between 2 tables

zarruq
  • 2,372
  • 2
  • 8
  • 19