jueves, 21 de mayo de 2020

Especificar Parametros Con: un Valor ó NULL; para FILTRAR el valor o traer todo





DECLARE @ID INT
SET @ID = NULL;


WITH T1
AS
(
SELECT ID = 1
UNION ALL
SELECT ID = 2
)

SELECT *
FROM T1
WHERE ID = @ID OR @ID IS NULL












Es este caso, como el parámetro tiene un valor NULL, regresa todo.


si el parámetro tuviera un valor,  filtraría bien ese valor.

viernes, 8 de mayo de 2020

Extraer estructura de una tabla temporal CTE



Obtiene las columnas (estructura) de una tabla temporal de un CTE



SELECT column_ordinal, name, system_type_name, max_length, precision, scale, collation_name, is_nullable
FROM sys.dm_exec_describe_first_result_set
(
N'
WITH RESERVAS
AS
(
 SELECT             *
 FROM        Hechos.OfertasServiciosConexos
 WHERE       Fecha               = ''2020-05-07''
 AND         ClaveGenerador      = ''07   CIP-U01''
)
SELECT       *
FROM         RESERVAS

'
, NULL, NULL);






FILAS EN UNA SOLA COLUMNA, SQL-T
















WITH ORDERS
 AS
 (
 select OrderId = 1,ProductId = 100
 union select 1,158
 union select 1,234
 union select 2,125
 union select 3,105
 union select 3,101
 union select 3,212
 union select 3,250
 )

 select distinct
       orderid
   ,REPLACE(LTRIM(REPLACE((  SELECT ' ' + CAST(ProductId as varchar)
       FROM ORDERS d
       WHERE d.OrderId = o.OrderId
       FOR XML PATH('')
   ),' ','')),' ', ', ') as Products
 from ORDERS o


RESULTADO:





PIVOT DINÁMICO USANDO CTE, WITH



-- ===================================================================
-- Autor:                 MANUEL OMAR OLGUÍN HERNÁNDEZ
-- Fecha:                 2020 MAYO 8
-- Versión:                1.0
-- Requerimiento:   PIVOT TABLE FORMED USING XML
-- Descripcion:            PIVOT TABLE sin necesidad de especificar explicitamente los nombres de las columnas
-- ================================================================
Select ID = 1, 'Tom' as Name ,'Bombadill' as Surname ,99999 as Age ,'Withywindle' as Address
UNION ALL
Select ID = 2, 'OMAR' as Name ,'OLGUIN' as Surname ,40 as Age ,'MEXICO' as Address






;with SampleCTE
as
(
Select ID = 1, 'Tom' as Name ,'Bombadill' as Surname ,99999 as Age ,'Withywindle' as Address
UNION ALL
Select ID = 2, 'OMAR' as Name ,'OLGUIN' as Surname ,40 as Age ,'MEXICO' as Address
)
Select A.ID, c.*
From SampleCTE A
Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
Cross Apply (
                    Select       Item = a.value('local-name(.)','varchar(100)') ,Value = a.value('.','varchar(max)')
                    From         B.XMLData.nodes('/row') as C1(n)
                    Cross Apply C1.n.nodes('./@*') as C2(a)
                    Where a.value('local-name(.)','varchar(100)') not in ('ID','ExcludeOtherCol')
                    ) C




















jueves, 20 de febrero de 2020

Rellenar Celdas con un Valor Anterior


tenemos una tabla como la siguiente:


queremos rellenar los Valor NULL con el último valor anterior conocido.




ejecutamos la siguiente query


-- CUENTA EL CAMPO QUE TIENE NULLS

    SELECT ID, v
        ,Cuenta=COUNT(v) OVER (ORDER BY ID)
    FROM #X




Este es el truco, va contando el número de valores encontrados:


ya solamente se necesita un SELECT MAX Particionado por la columna "Cuenta".








SELECT ID, v, s=MAX(v) OVER (PARTITION BY cuenta)
FROM
(
    SELECT ID, v
        ,Cuenta=COUNT(v) OVER (ORDER BY ID)
    FROM #X
) a
ORDER BY ID;








source:













lunes, 21 de enero de 2019

AGRUPACIÓN POR UN CAMPO, ÚNICAMERNTE CUANDO ÉSTE ES CONSECUTIVO ENTRE SI


CÓMO AGRUPAR POR NODO ÚNICAMENTE CUANDO LOS NODOS ESTÁN CONSECUTIVOS ENTRE SI


CÓMO AGRUPAR POR NODO ÚNICAMENTE CUANDO LOS NODOS ESTÁN CONSECUTIVOS ENTRE SI


NODO   ID_GENERAL    ID_AGRUPADO_X_NODO      RESTA ( ID_GENERAL-ID_AGRUPADO_X_NODO)

 X           1             1                        0
 X           2             2                        0
 X           3             3                        0
 Y           4             1                        3
 Y           5             2                        3
           6             3                        3
           7             1                        6
           8             2                        6
           9             1                        8



SALUDOS