Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - The multi-row query results of one-to-many relationship in sql are converted into one row and multiple columns.
The multi-row query results of one-to-many relationship in sql are converted into one row and multiple columns.
1, create a test table,

Create table test_fee(userid number, feeid number, feeid number);

2. Insert test data

Insert into the test_fee value (1, 100 1, 80);

Insert into the test_fee value (1,1002,70);

Insert into the test_fee value (1,1003,90);

Insert into the test_fee value (1,1004,60);

Insert into the test_fee value (2, 100 1 99);

Insert into the test_fee value (2, 1002, 66);

Insert into the test_fee value (2, 100 1 55);

3. Query all records in the table, select t.*, rowid from test_fee t,

4. Write sql, summarize by userid, and summarize by column according to different feeid.

Select user id,

Sum (when Feeid =1001,and then fee else 0 end) is taken as fee_ 100 1,

Sum(feeid = 1002, and then fee else 0 end) as fee_ 1002,

Sum(feeid = 1003, and then fee else 0 end) as fee_ 1003,

Sum (when feeid = 1004, fee else 0 end) is fee_ 1004.

From the test cost test

Group by user id