Skip to content
Advertisement

SQL query to display column values as column name in table

I have a field name ‘Title’ from table ‘Greeting’. Title field in UI might come as FirstName or LastName or combination of both.

Greeting table looks like:

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
</head>
<body>

<h2>Collapsed Borders</h2>
<p>If you want the borders to collapse into one border, add the CSS border-collapse property.</p>

<table style="width:50%">
  <tr>
    <th>Title</th>
  </tr>
  <tr>
    <td>FirstName</td>
  </tr>
  <tr>
    <td>LastName</td>
  </tr>
  <tr>
    <td>nickName</td>
  </tr>
  <tr>
    <td>preferredName</td>
  </tr>
</table>

</body>
</html>

I need to write a SQL Query to find which has Title FirstName only, LastName only and both FirstName and LastName and display in below table format. Create column name as FirstName and lastName and indicate by ‘Yes’ if that displayed and ‘No’ if not displayed.

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
</head>
<body>

<h2>Collapsed Borders</h2>
<p>If you want the borders to collapse into one border, add the CSS border-collapse property.</p>

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
  </tr>
  <tr>
    <td>Yes</td>
    <td>No</td>
  </tr>
  <tr>
    <td>No</td>
    <td>Yes</td>
  </tr>
  <tr>
    <td>Yes</td>
    <td>Yes</td>
  </tr>
</table>

</body>
</html>

I wrote below query and got the individual information of the ‘Title’ but not able to get column values as table column name format. Could you please help me to get output data in that table format

Select distinct Title from Greeting  WHERE  Title in ('FirstName','LastName') 
Select distinct Title from Greeting  WHERE  Title ='FirstName'
Select distinct Title from Greeting  WHERE  Title = 'LastName'

Advertisement

Answer

I tried ‘pivot’ and that helped me to get get output data in that table format

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement