Ir al contenido principal

SQL Server - Tips II

Uso de CTE


Especifica un conjunto de resultados temporal con nombre, conocido como expresión de tabla común (CTE). Se deriva de una consulta simple y se define en el ámbito de ejecución de una sola instrucción SELECT, INSERT, UPDATE o DELETE. Esta cláusula también se puede utilizar en una instrucción CREATE VIEW como parte de la instrucción SELECT que la define. Una expresión de tabla común puede incluir referencias a ella misma. Esto se conoce como expresión de tabla común recursiva.

Ejemplo


WITH Sales_CTE (SalesPersonID, NumberOfOrders)
AS
(
    SELECT SalesPersonID, COUNT(*)
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
    GROUP BY SalesPersonID
)
SELECT AVG(NumberOfOrders) AS "Average Sales Per Person"
FROM Sales_CTE;
GO

Using multiple CTEs

WITH Sales_CTE 
AS
(

) ,New CTE
as (

)
select *
from Sales_CTE , New CTE 

Using parameters

DECLARE @somevar DECIMAL;
WITH SomeName AS (SELECT....)
SELECT @somevar = ...
FROM SomeName


Sum a previous record

insert into table1 
values
(1,100.00 , date '2013-01-01'),  
(1,150.00 , date '2013-01-02'),
(1,200.00 , date '2013-01-03'),
(2,75.00  , date '2013-01-01'),

(2,100.00 , date '2013-01-02');


account_numberbillbill_datesum_to_dateaccount_total
1   100    January, 01 2013 00:00:00    100450
1   150January, 02 2013 00:00:00    250450
1   200January, 03 2013 00:00:00    450450
2   75January, 01 2013 00:00:00    75175
2  100January, 02 2013 00:00:00      175175

SELECT Account_Number, 
       Bill, 
       Bill_Date, 
       sum(bill) over (partition by account_number order by bill_date) as sum_to_date,
       SUM(Bill) over (partition by account_Number) as account_total
FROM Table1
order by account_number, bill_date;

Pivot - Display horizontal rows to vertical align 


Change the order of the columns to an horizontal view

 ->

This is an example for a static case, due to the number of kpis_rem_prov_tgt_vol is known

select [reme_rem_target_month] , [1], [0]
from (
    INTERN SELECT ....
    select
Analysis.[reme_rem_target_month]
,sum ([kpis_crs_vol]) as CSR_Vol
,[kpis_rem_prov_tgt_vol]
    from ....


)Results //Alias of the intern select
pivot (
sum (CSR_Vol)  for [kpis_rem_prov_tgt_vol] in ([0], [1])
)t

In this case [kpis_rem_prov_tgt_vol] is the field to be used as pivot, and their results will be the new headers.
sum (CSR_Vol) are the values to be grouped, in this case any add is performed.
[reme_rem_target_month] this field will be grouped automatically.



CASE using like in the conditions


case  
when t.[resto_rst_target_month] like '%January%' then 1
when t.[resto_rst_target_month] like '%February%' then 2
when t.[resto_rst_target_month] like '%March%' then 3
when t.[resto_rst_target_month] like '%April%' then 4
when t.[resto_rst_target_month] like '%May%' then 5
when t.[resto_rst_target_month] like '%June%' then 6

end


Comentarios

Entradas populares de este blog

Android - Basic Steps (Service)

Service Run in the main thread of the hosting application Android can kill the Service if need the resources Purpose Supporting inter-application method execution Performing background processing Start a Service Call Context.startService(Intent intent)\ To call from a Fragment use getActivity().getApplicationContext().startService( intentService); Executing the service After call startService(...)  In the Service is executed the method onStartCommand(...) If the method returns the constant START_NOT_STICKY then Android will not restart the service automatically if the the process is killedp Foreground To execute the service foreground call the method startForeground() Use this if the user is aware of the process Bind to a Service Call the method Context.bindService( Intent service ServiceConnection con int flags ) Send Toast from the Service On the method onStartCommand receive the message   ...

Android - Basic Steps (Location & Maps)

Location Is composed by Latitude Longitude Time-stamp Accuracy Altitude Speed Bearing LocationProvider Types: Network  Wifi access points Cell phone towers GPS Passive Piggyback on the readings requested by other application Permissions Network  android.permission.ACCESS_COARSE_LOCATION android.permission.ACCESS_FINE_LOCATION GPS android.permission.ACCESS_FINE_LOCATION Passive Provider android.permission.ACCESS_FINE_LOCATION LocationManager System service for accessing location data getSystemService( Context.LOCATION_SERVICE ) Functions Determine the last known user location Register for location update Register to receive intents when the device nears or move away from a given geographic area LocationListener Defines callbacks methods that are called when Location or LocationProvider status change. Methods onLocationChanged(...) onProviderDisabled(...) onProviderEnabled(...) onStatusChan...

IIS - Permisions

IIS Permissions To enable the Active Directory connection in the IIS, follow the next steps: Go to IIS Go to Application Pool Select your App Pool Select Advanced Settings in the right side In the section Process Model Select in Identity value the property " NetworkService " You don´t need to restart your application