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

C# Using tabs

To use tabs in C# use the TabContainer element from AjaxControlToolkit Include AjaxControlToolkit  Include in the Web.config file, inside the tag <system.web> the following code  <pages>       <controls>         <add tagPrefix="ajaxCTK" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit"/>       </controls>     </pages>   Include TabContainer element First  include TabContainer element that is the section where all the tabs will be displayed. <ajaxCTK:TabContainer ID="TabContainerUpdate" runat="server"                 Height="800"                 CssClass="ajax__tab_style"> </ajaxCTK:TabContainer> Second per each tab include the following code corresponding to each ...

Python create package

Create a root folder Create a sub-folder "example_pkg" that contains the funtionallity packaging_tutorial/ example_pkg/ __init__.py In the root folder create the following structure  packaging_tutorial/ example_pkg/ __init__.py tests/ setup.py LICENSE README.md in the setup.py contains the configuration of the packages your package is found by find_packages() import setuptools with open ( "README.md" , "r" ) as fh : long_description = fh . read () setuptools . setup ( name = "example-pkg-YOUR-USERNAME-HERE" , # Replace with your own username version = "0.0.1" , author = "Example Author" , author_email = "author@example.com" , description = "A small example package" , long_description = long_description , long_description_content_type = "text/markdown" , url = "https://github.com/pypa/sam...

Rails - Basic Steps III

pValidations Validations are a type of ActiveRecord Validations are defined in our models Implement Validations Go to   root_app/app/models Open files  *.rb for each model Mandatory field validates_presence_of   :field Ex:   validates_presence_of    :title Classes The basic syntax is class MyClass        @global_variable                def my_method              @method_variable        end end Create an instance myInstance = MyClass.new Invoke a mehod mc.my_method class() method returns the type of the object In Ruby, last character of method define the behavior If ends with a question -> return a boolean value If ends with an exclamation -> change the state of the object Getter / Setter method def global_variable       return @global_variable end ...