To make things more clear, let us first create a sample table
CREATE TABLE table_test(
ID INT,
Item VARCHAR(100),
Amount DOUBLE,
Item_Mode VARCHAR(10)
);
Now we can enter some sample data
INSERT INTO `table_test`(`ID`,`Item`,`Amount`,`Item_Mode`) VALUES
(1,'Allowances',100.00,'a'),
(2,'HRA',200.00,'a'),
(3,'DA',100.00,'a'),
(4,'FBP',100.00,'a'),
(5,'Income Tax',50.00,'d'),
(6,'Insurance ',10.00,'d'),
(7,'Provident Fund',20.00,'d');
We have two types of data here. Mode a and Mode d.
ID | Item | Amount | Item_Mode |
---|---|---|---|
1 | Allowance | 100.00 | a |
2 | HRA | 200.00 | a |
3 | DA | 100.00 | a |
4 | FBP | 100.00 | a |
5 | Income Tax | 50.00 | d |
6 | Insurance | 10.00 | d |
7 | Provident Fund | 20.00 | d |
I want to show it all the ‘a’ data in one column and all the ‘d’ data in next column. How can I achieve this.
I tried
SELECT A.Item AS EARN,B.Item AS DEDUCT
FROM Table A INNER JOIN TABLE B
ON A.ID = B.ID WHERE MOD(A.ID,2)=1 AND A.Mode = 'a' OR B.Mode = 'd'
The above query pumped out a wrong answer.
The expected dataset must display data like below
IDA | ItemA | AmountA | Item_ModeA | IDB | ItemB | AmountB | Item_ModeB |
---|---|---|---|---|---|---|---|
1 | Allowance | 100.00 | a | 5 | Income Tax | 50.00 | d |
2 | HRA | 200.00 | a | 6 | Insurance | 10.00 | d |
3 | DA | 100.00 | a | 7 | Provident Fund | 20.00 | d |
4 | FBP | 100.00 | a |
2
Answers
You can use the next
SELECT
statement:Note: if count of rows in the
group_b
is bigger, then you can lose the data due toLEFT JOIN
.Update
If counts of these two parts are different time-to-time, then you can change the last two lines:
Update
For the MySQL 5.5
Here:
LEFT JOIN and RIGHT JOIN instead of FULL OUTER JOIN
UNION to combine the results of the left and right joins
subqueries to compute the row numbers instead of the OVER() clause
Assuming the number of items
a
always 4 and higher than number of itemsd
, then you can do it usingself left join
with a condition(a.ID mod 4) = (b.ID mod 4)
If we take this query :
it will Result :
As you can see the first record with item
a
can be matched with first itemd
because both havingID mod 4 = 1
So the query can be :
Result :
Demo here
If the number of rows of items a and d can be any number then :
First
cte
used to group items by mode.Second
cte
will find the item with the highest number of rows(in the simple data it isa
with 4 items).item_mode_with_more_rows
to get set of records from the biggest mode.item_mode_with_less_rows
to get set of records from the smallest mode.Then using a
left join
we get the expected outputDemo here