sql >> Database teknologi >  >> RDS >> Sqlserver

group_concat i SQL Server 2012 med ORDER BY en anden kolonne

Jeg er ikke sikker på, om dette vil være hurtigere, men her er en alternativ version, hvor du ikke deltager på purchases to gange i STUFF() :

select customer_id,
  min(purchased_at) as first_purchased_at,
  stuff ((select ',' +  p2.product 
          from
          (
            select product, customer_id,
                ROW_NUMBER() over(partition by customer_id, product order by purchased_at) rn,
                ROW_NUMBER() over(partition by customer_id order by purchased_at) rnk   
            from purchases
          ) p2 
          where p2.customer_id = p1.customer_id
            and p2.rn = 1
          group by p2.product, rn, rnk
          order by rnk
          for XML PATH('') ), 1,1,'') AS all_purchased_products  
from purchases p1
group by customer_id;

Se SQL Fiddle with Demo

Resultat:

| CUSTOMER_ID |               FIRST_PURCHASED_AT | ALL_PURCHASED_PRODUCTS |
---------------------------------------------------------------------------
|           1 |      June, 01 2012 00:00:00+0000 |           apples,pears |
|           2 |      June, 01 2012 00:00:00+0000 |                 apples |
|           3 | September, 02 2012 00:00:00+0000 |   pears,apples,bananas |



  1. mysql:hvordan gemmer man ORDER BY efter LEFT JOIN uden genbestilling?

  2. Opdater et felt i en eksisterende tabel med Auto Increment Logic

  3. Hvorfor fungerer pi()-funktionen ikke i Oracle ved at bruge dens JDBC-driver?

  4. MySQL slutter sig kun til udvalgte rækker