/*
    KÖTID FRÅN BOKÖ TILLS MAN SKRIVIT AVTAL. EJ INFLYTTNING!
    VILKEN SORTERING/GRUPPERING SKALL DET VARA?
    VILKA PARAMETRAR SKALL SÄTTAS UPP?
    VEM FIXAR LAYOUTEN?
*/

SELECT
    OBJ.OBJ_OBOTYP,
    OBJ.OBJ_OBJNR,
    OBJ.OBJ_BOSOK1_OMR_BCD,
    CAST(LEFT(RIGHT(SPIN_TEXT, LEN(SPIN_TEXT) - CHARINDEX('inflyttning: ', SPIN_TEXT, 1) - 12),8) AS DATE) AS 'Ködatum',
    CAST(SPIN_DATESTAMP_NY AS DATE) AS 'Borttagen',
    DATEDIFF(dd,CAST(LEFT(RIGHT(SPIN_TEXT, LEN(SPIN_TEXT) - CHARINDEX('inflyttning: ', SPIN_TEXT, 1) - 12), 8) AS DATE),CAST(SPIN_DATESTAMP_NY AS DATE)) AS dagar
    --AVG(DATEDIFF(dd,CAST(LEFT(RIGHT(SPIN_TEXT, LEN(SPIN_TEXT) - CHARINDEX('inflyttning: ', SPIN_TEXT, 1) - 12), 8) AS DATE),CAST(SPIN_DATESTAMP_NY AS DATE))) AS 'snitt'
FROM
    SPIN
    INNER JOIN PKU ON SPIN.SPIN_PARENT_KEY = PKU_KUNDNRINTERN
    INNER JOIN OBJ ON PKU.PKU_KUNDNR = OBJ.OBJ_KUNDNR
WHERE
    SPIN_SOKNAMN LIKE 'Borttagen%'
    AND SPIN_TEXT LIKE '%Köplats%borttagen%inflyttning%'
    AND SPIN_TYP = 'BOKO'
    AND YEAR(SPIN_DATESTAMP_NY) >= '2022'
    AND OBJ.OBJ_OBJTYP LIKE 'B%'
    --AND SPIN_TEXT LIKE '%intern:62120%' -- Alex interna kundnr

SELECT TOP 1 * FROM SPIN WHERE SPIN_TYP = 'BOKO' AND SPIN_SOKNAMN LIKE 'Borttagen%'

SELECT * FROM SPIN WHERE SPIN_PARENT_KEY = '62120'