sql >> Database >  >> RDS >> Sqlserver

COALESCE gebruiken in de SQL-weergave

BEWERKEN :Aangepast antwoord om het maken van een weergave op te nemen.

/* Set up sample data */
create table Customers (
    CustomerId int,
    CustomerName VARCHAR(100)
)

create table Orders (
    CustomerId int,
    OrderName VARCHAR(100)
)

insert into Customers
    (CustomerId, CustomerName)
    select 1, 'John' union all
    select 2, 'Marry'

insert into Orders
    (CustomerId, OrderName)
    select 1, 'New Hat' union all
    select 1, 'New Book' union all
    select 1, 'New Phone'
go

/* Create the view */       
create view OrderView as    
    select c.CustomerName, x.OrderNames
        from Customers c
            cross apply (select stuff((select ',' + OrderName from Orders o where o.CustomerId = c.CustomerId for xml path('')),1,1,'') as OrderNames) x
go

/* Demo the view */
select * from OrderView
go 

/* Clean up after demo */
drop view OrderView
drop table Customers
drop table Orders
go


  1. Hoe query postgre te optimaliseren

  2. LAAD GEGEVENS LOKAAL INFILE verboden in... PHP

  3. Verken SQL Server Restore Database met opties voor herstel versus geen herstel

  4. Hoe krijg ik een ID in MSSQL in PHP?