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 (Notifications)

User Notifications Types: Toast Notification Area Notifications Tip To use the notification vibration, establish the permission in the AndroidManifest.xml file    <uses-permission android:name="android.permission.VIBRATE" >     </uses-permission> Broadcast Base class for components that receive and react to events When event occur is represented as Intent, then are broadcast to system The Intent routes to BroadcastReceiver The BroadcastReceiver receive on the method onReceive() Broadcast Events can be broadcast in Order or Normal way Normal - Undefined order and if there are two or more BroadcastReceivers can process the event at the same time. Order - Deliver the intent one at the time in priority order Can also be Sticky or Not Sticky Sticky   Store intent after initial broadcast Is useful to record system changes like the battery status Is disposed after the event finish  Non Stick...

BI - SSIS ( Basics I )

SSIS - Basic Concepts Tasks Bulk Insert Task—Loads data into a table by using the BULK INSERT SQL command. Data Flow Task—This is the most important task that loads and transforms data into an OLE DB Destination. Execute Package Task—Enables you to execute a package from within a package, making your SSIS packages modular. Execute Process Task—Executes a program external to your package, like one to split your extract file into many files before processing the individual files. Execute SQL Task—Executes a SQL statement or stored procedure. File System Task—This task can handle directory operations like creating, renaming, or deleting a directory. It can also manage file operations like moving, copying, or deleting files. FTP Task—Sends or receives files from an FTP site. Script Task—Runs a set of VB.NET or C# coding inside a Visual Studio environment. Send Mail Task—Sends a mail message through SMTP. Analysis Services Processing Task—This task processes a SQL Server A...

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   ...