Skip to content
Advertisement

how to SQL select with join from two tables and get one json object

Please I am working on a project and I am kind of stuck in this.

My SELECT is as simple as this:

SELECT TOP 1 
  co.[contactid] AS [c.id], 
  co.[firstname] + ' ' + co.[lastname] AS [c.fullname], 
  f.[name] AS [p.name], 
  f.[username] AS [p.username], 
  f.[date] AS [p.startDate] 
FROM [dbo].[table1] co 
JOIN [dbo].[table2] f ON co.[contactid] = f.[contact_id] 
WHERE co.[lastname] LIKE 'last%' 
FOR JSON AUTO

and I get :

[{
"c.id": "1",
"c.fullname": "firstname lastname",
"f": [
  {
    "p.name": "name1",
    "p.username": "Username1",
    "p.startDate": "2015-06-15"
  }
]}]

I would like the result to be:

[{
  "c.id": "1",
  "c.fullname": "firstname lastname",
  "p.name": "name1",
  "p.username": "Username1",
  "p.startDate": "2015-06-15"
}]

Advertisement

Answer

You can use this code:

SELECT *
FROM    
    (SELECT TOP 1 
         co.[contactid]  AS [c.id],
         co.[firstname] + ' ' + co.[lastname] AS [c.fullname],
         f.[name]        AS [p.name],
         f.[username]    AS [p.username],
         f.[date]        AS [p.startDate]
     FROM   
         [dbo].[table1] co
     JOIN 
         [dbo].[table2] f ON co.[contactid] = f.[contact_id]
     WHERE  
         co.[lastname] LIKE 'last%') a           
FOR JSON AUTO
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement