R
R
raswe2020-05-04 14:22:59
SQL Server
raswe, 2020-05-04 14:22:59

How to collect customer data in one record?

There is a table with customers and the dates of formation and completion of the order, of the form

ID	NAME	BEGIN	        END
234	SOKOL	01.02.2020	08.02.2020
145	EVA	        03.02.2020	06.02.2020
145 	EVA	        16.02.2020	20.02.2020

It is necessary to collect a single pivot table
ID	NAME	BEGIN1	         END1	          BEGIN2	         END2	      BEGIN3	     END3
234	SOKOL	01.02.2020	08.02.2020				
145	EVA	        03.02.2020	06.02.2020	16.02.2020	20.02.2020

We do not know which customer which month will have how many orders, who will have 1 per month, who will have three. It is necessary that the request itself collects data for each customer in one line.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2020-05-04
@raswe

Track portions of unfilled periods.

Intervals and counters , with aggregate and window functions. Intervals and counters, all parts .
Clarifying the essence of the issue:
Either collect a dynamic query, or use PIVOT .
If you build a dynamic query, then first calculate how many periods-columns will be. First columns - select unique, period columns from aliases with appropriate filters.
But literally:
It is necessary that the request itself collects data for each customer in one line.

DECLARE @T TABLE ( ID INT, [Name] VARCHAR(50), [Begin] DATE, [End] DATE)
INSERT @T VALUES ( 234, 'SOKOL', '01.02.2020', '08.02.2020' ),
(145, 'EVA', '03.02.2020', '06.02.2020'),
(145, 'EVA', '16.02.2020', '20.02.2020')

SELECT ID, [Name], 
       STRING_AGG( CONVERT(VARCHAR, [Begin], 104) + '~' + 
                   CONVERT(VARCHAR, [End], 104), ', ') 
                      WITHIN GROUP (ORDER BY [Begin] ) AS [Orders]
  FROM @T 
  GROUP BY ID, [Name]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question