Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello

please I need your help.
I am trying to make a view in SQL, first if I have this table:

ID Po
1 A
2 A
3 A
4 B
5 A
6 C
7 D
8 E

How can I make a view using select to and the view will give me the table like this:

ID Po A Po B Po C Po D Po E
1 A B C D E
2 A - - - -
3 A - - - -
4 A - - - -

and here the ID will be auto increment.

I hope it's clear. I am sorry but I tried a lot to solve this and I really need it so please guys help me.

Thank a lot for every things

What I have tried:

I didn't find the good way and all my tried were very far from what I am looking
Posted
Updated 4-Jul-18 21:52pm
v2
Comments
[no name] 4-Jul-18 15:29pm    
The keyword is "Pivot". You can Google for it "SQL pivot". I'm not familiar with it, but I'm more or less sure you will get more or less soon an answer here ;)
Member 13898659 4-Jul-18 16:42pm    
Thanks a lot :)

1 solution

It's not at all clear how to get from your source data to your expected data as the data in the final table does not represent what was in your original.

However, as @0x01AA stated, you need to use a PIVOT at some point. There is a short tip here on CodeProject that gives a nice simple example:Simple Way To Use Pivot In SQL Query[^]

Here is an example of what you might want to do with your source data:
SQL
create table #demo (ID integer identity(1,1), Po varchar(10))
insert into #demo (Po) values
('A'), ('A'), ('A'), ('B'), ('A'), ('C'), ('D'), ('E')

SELECT *
FROM (
    SELECT ID, Po
        FROM #demo
) as s
PIVOT
(
    COUNT(ID)
    FOR [Po] IN (A, B, C, D, E)
)AS pvt
Which gives the results
A	B	C	D	E
4	1	1	1	1
If you want to do other stuff you might want to put this into a Common Table Expression (CTE) see SQL Wizardry Part Three - Common Table Expressions (CTEs)[^]

You also mentioned an auto-increment ID in your results. It is unlikely that this is going to be the ID from your table... a good way of getting a similar result in results is to use the ROW_NUMBER[^] function. Here is a trivial example using the same data as above:
SQL
SELECT ID, Po, ROW_NUMBER() OVER (ORDER BY ID DESC)
FROM #demo
ORDER BY ID

If I'm way off base with this just reply and I'll try to help further
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900