0

Trying to figure how to write a pivot sql server statement. I have following table

Source Table

ID |Product |Event        |Date 
-----------------------------------------------
1  |Laptop  |Search       |2020-07-17 14:41:13.535
1  |Laptop  |Product Page |2020-07-17 14:41:13.535
1  |Laptop  |Bought       |2020-07-17 14:41:13.535
1  |Tablet  |Search       |2020-07-18 14:41:13.535
1  |Tablet  |Product Page |2020-07-18 14:41:13.535
1  |Tablet  |Bought       |2020-07-18 14:41:13.535

Desired Output

 ID|   Product |Search                  |Product Page             |Bought
-----------------------------------------------------------------------------------------------
 1 |   Laptop  |2020-07-17 14:41:13.535 |2020-07-17 14:41:13.535  |2020-07-17 14:41:13.535
 1 |   Tablet  |2020-07-18 14:41:13.535 |2020-07-18 14:41:13.535  |2020-07-18 14:41:13.535

My Query looks like

with V1 as 
(
select id,product,event,start_time_local
from table1
)
select id,product,
[search],[product page],[Bought] from V1
PIVOT (Max(start_time_local) for event_type in ([search],[product page],[Bought]))
as PivotTable;

When i take Max(date) it returns with only max value wherein i want to display all dates.

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Pivoting is a form of aggregation, you can't `PIVOT`/Cross tab and *not* aggregate. End of Story. – Thom A Feb 12 '21 at 13:46

1 Answers1

1

As I mentioned in the comment, you can't PIVOT/Cross Tag without aggregating as it is a form of aggregation. Personally, however, I recommend using the latter (also known as conditional aggregation), as it's far less restrictive. Then you can do the following:

SELECT ID,
       Product,
       MAX(CASE Event WHEN 'Search' THEN Date END) AS Search,
       MAX(CASE Event WHEN 'Product Page' THEN Date END) AS ProductPage,
       MAX(CASE Event WHEN 'BOught' THEN Date END) AS Bough
FROM (VALUES(1,'Laptop','Search      ','2020-07-17T14:41:13.535'),
            (1,'Laptop','Product Page','2020-07-17T14:41:13.535'),
            (1,'Laptop','Bought      ','2020-07-17T14:41:13.535'),
            (1,'Tablet','Search      ','2020-07-18T14:41:13.535'),
            (1,'Tablet','Product Page','2020-07-18T14:41:13.535'),
            (1,'Tablet','Bought      ','2020-07-18T14:41:13.535'))V(ID,Product,Event,Date)
GROUP BY ID,
         Product;
Thom A
  • 88,727
  • 11
  • 45
  • 75