how i can pivot data in sql with c#

amir 20 Reputation points
2024-02-07T03:17:09.3566667+00:00

I have a table in my SQL Server database named 'UserDetails,' where the data is stored row-wise. Now, I need to generate a report where this data is returned in a column-wise format. For instance, the 'UserDetails' table has columns like 'firstname,' 'lastname,' and 'phone' as keys, storing information row-wise. How can I retrieve this data in a column-wise format from the database for reporting purposes?

SQL Server Other
Developer technologies C#
{count} votes

Accepted answer
  1. hossein jalilian 10,825 Reputation points Volunteer Moderator
    2024-02-07T03:22:54.2933333+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    Here's an example query that demonstrates how to achieve this:

    var result = await _userDetails.Table
        .GroupBy(x => x.userId)
        .Select(x => new
        {
            UserId = x.Key,
            FirstName = x.FirstOrDefault(item => item.Key == "FirstName").Value ?? "",
            LastName = x.FirstOrDefault(item => item.Key == "LastName").Value ?? "",
            Phone = x.FirstOrDefault(item => item.Key == "Phone").Value ?? ""
        })
        .ToDictionaryAsync(x => x.UserId, x => new
        {
            FirstName = x.FirstName,
            LastName = x.LastName,
            Phone = x.Phone
        });
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.