Wednesday, September 3, 2025

SQL - Query Analytics Basic

 SELECT Nome_Produto,

ROUND(MIN(Valor_Venda), 2) AS Valor_Minimo, ROUND(MAX(Valor_Venda), 2) AS Valor_Maximo, ROUND(AVG(Valor_Venda), 2) AS Valor_Medio, ROUND(SUM(Valor_Venda), 2) AS Valor_Total, COUNT(Valor_Venda) AS Contagem, Ano FROM TB_DSA_VENDAS, TB_DSA_PRODUTOS, TB_DSA_PEDIDOS WHERE TB_DSA_VENDAS.Produto = TB_DSA_PRODUTOS.ID_Produto AND TB_DSA_VENDAS.Pedido = TB_DSA_PEDIDOS.ID_Pedido GROUP BY Produto, Ano ORDER BY Contagem DESC;

Tuesday, March 11, 2025

Power Query - funcao limpa replace texto numero

//fnc_limpa_numeros

(TextValue as nullable text) =>

let

    SafeText = if TextValue = null then "" else TextValue,

    DigitsOnly = Text.Combine(

        List.Select(Text.ToList(SafeText), each Text.Contains("0123456789", _))

    )

in

    DigitsOnly

    

//fnc_limpa_text

(TextValue as nullable text) =>

let

    SafeText = if TextValue = null then "" else TextValue,


    // Tabela com caracteres acentuados e suas substituições

    AccentsList = {

        {"à","a"},{"á","a"},{"â","a"},{"ã","a"},{"ä","a"},

        {"è","e"},{"é","e"},{"ê","e"},{"ë","e"},

        {"ì","i"},{"í","i"},{"î","i"},{"ï","i"},

        {"ò","o"},{"ó","o"},{"ô","o"},{"õ","o"},{"ö","o"},

        {"ù","u"},{"ú","u"},{"û","u"},{"ü","u"},

        {"À","A"},{"Á","A"},{"Â","A"},{"Ã","A"},{"Ä","A"},

        {"È","E"},{"É","E"},{"Ê","E"},{"Ë","E"},

        {"Ì","I"},{"Í","I"},{"Î","I"},{"Ï","I"},

        {"Ò","O"},{"Ó","O"},{"Ô","O"},{"Õ","O"},{"Ö","O"},

        {"Ù","U"},{"Ú","U"},{"Û","U"},{"Ü","U"},

        {"ç","c"},{"Ç","C"},{"ñ","n"},{"Ñ","N"}

    },


    // Primeiro remove os acentos explicitamente

    WithoutAccents = List.Accumulate(

        AccentsList, 

        SafeText, 

        (text, pair) => Text.Replace(text, pair{0}, pair{1})

    ),


    // Remove todos os caracteres não alfabéticos (pontuação, especiais, números)

    CleanedText = Text.Combine(

        List.Select(

            Text.ToList(WithoutAccents), 

            each Text.Contains("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", _)

        ), ""

    )

in

    CleanedText   

Chamada: = Table.TransformColumns(#"Uppercased Text", {{"NAME", fnc_limpa_text}})

Friday, February 28, 2025

Power Query - fnc funcao Date

   #"Changed column type" = Table.TransformColumnTypes(#"Renamed columns2", {{"INÍCIO DO ANO LETIVO", Int64.Type}, {"INÍCIO DO RECESSO", Int64.Type}, {"FIM DO ANO LETIVO", Int64.Type}, {"FIM DO RECESSO", Int64.Type}}),

  #"Lowercased text" = Table.TransformColumns(#"Changed column type", {{"INÍCIO DO ANO LETIVO", each Date.AddDays(DataBase, Number.FromText(Text.From(_))), type date}}),
  #"Lowercased text 1" = Table.TransformColumns(#"Lowercased text", {{"INÍCIO DO RECESSO",  each Date.AddDays(DataBase, Number.FromText(Text.From(_))), type date}}),
  #"Lowercased text 2" = Table.TransformColumns(#"Lowercased text 1", {{"FIM DO ANO LETIVO",  each Date.AddDays(DataBase, Number.FromText(Text.From(_))), type date}}),
  #"Lowercased text 3" = Table.TransformColumns(#"Lowercased text 2", {{"FIM DO RECESSO",  each Date.AddDays(DataBase, Number.FromText(Text.From(_))), type date}})
in
  #"Lowercased text 3"

Friday, April 5, 2024

Power Query - Calculate Between RATE x HOURS

     //Carrega tab Faturamento 

    #"Added Custom" = Table.AddColumn(FAT_Faturamento_Table, "Referencia", each "01_Prio"),

    //Carrega tab Rate 

    Rate_Faturamento_Table = DIM_TaxWallet_csv_DF,


    // Merge entre os datasets com base na referência e data

    Merged_Table = Table.Join(#"Added Custom", "Referencia", Rate_Faturamento_Table, "Referencia"),

    // Ajusta tipos de datas

    #"Changed Type2" = Table.TransformColumnTypes(Merged_Table,{{"DataFinal", type text}, {"DataInicial", type text}}),

    #"Changed Type" = Table.TransformColumnTypes(#"Changed Type2",{{"DataInicial", type date}, {"DataFinal", type date}, {"dt_Aberto", type date}}),

    // Criar validação da Rate Between

    #"Added Conditional Column" = Table.AddColumn(#"Changed Type", "Valid_DateRate", each if ([dt_Aberto] >= [DataInicial] and [dt_Aberto] <= [DataFinal]) then "Y" else "N"),

    // Considera apenas validação Y 

    #"Filtered Rows" = Table.SelectRows(#"Added Conditional Column", each ([Valid_DateRate] = "Y")),

    // Então Calcula Rate x Horas

    #"Added Custom1" = Table.AddColumn(#"Filtered Rows", "VlrCostEstimadoTicket", each [ValorHora] * [VlrEst_Prio]),

Friday, December 8, 2023

Script para executar scripts Google Colab

 script.bat

@echo off

powershell -ExecutionPolicy Bypass -File "D:\script.ps1"


script.ps1

# Defina a URL do link

$url = "https://colab.research.google.com/drive/sdfdsfgghjdghjgh"

# Inicie o Google Chrome

Start-Process "chrome.exe" -ArgumentList $url -PassThru | Wait-Process

# Aguarde um momento para o Chrome abrir completamente

Start-Sleep -Seconds 22

# Envie o atalho de teclado Ctrl+F9

Add-Type -AssemblyName System.Windows.Forms

[System.Windows.Forms.SendKeys]::SendWait("^{F9}")


Thursday, August 3, 2023

Power Query - Valid Is Number

 let

    origem = TabelaExemplo, // Fonte da tabela

    selecionarNumericos = Table.SelectRows(origem, each Value.Is(Value.FromText([ColunaValores]), type number)) // Filtrar apenas valores numéricos

in

    selecionarNumericos


Thursday, July 6, 2023

Power Query & SQL - Grouping Max Value ( Group by Group)

 script Power Query:

let

Source = Table.Combine({FAT_SAP_Lista_3, FAT_SAP_Lista_4}),

Step1 = Table.Group(Source, {"CUSTOMER"}, {{"MaxDate", each List.Max([DATEFROM]), type datetime}}),

Step2 = Table.Join(Source, {"CUSTOMER", "DATEFROM"}, Step1, {"CUSTOMER", "MaxDate"}),

Step3 = Table.SelectColumns(Step2,{"Source", "SHIP_COND", "KNVAL", "DATEFROM", "DATETO", "/BIC/ZMATERIAL", "CUSTOMER", "KNART","SALES_GRP"})

in

Step3


==============================

script SQL New:

WITH Source AS ( SELECT * FROM ( SELECT * FROM FAT_SAP_Lista_3 UNION ALL SELECT * FROM FAT_SAP_Lista_4 ) AS combined ), Step1 AS ( SELECT CUSTOMER, MAX(DATEFROM) AS MaxDate FROM Source GROUP BY CUSTOMER ), Step2 AS ( SELECT s.* FROM Source s INNER JOIN Step1 ON s.CUSTOMER = Step1.CUSTOMER AND s.DATEFROM = Step1.MaxDate ), Step3 AS ( SELECT Source, SHIP_COND, KNVAL, DATEFROM, DATETO, /BIC/ZMATERIAL, CUSTOMER, KNART, SALES_GRP FROM Step2 ) SELECT * FROM Step3;

==============================

script SQL Old:

???

Tuesday, June 6, 2023

Tabular Editor Advanced - Convert Measures Filters (Medidas em Filtros)

 



Install Tabular Editor:
https://tabulareditor.com/

https://www.sqlbi.com/tools/tabular-editor/

https://github.com/TabularEditor/TabularEditor/releases/tag/2.24.1


1 - Go to Table, create New calculation Group
2 - Rename "Name"
3 - Create New Calculations Items (...)
4 - Config each New Calculation Item (Print)
5 - Save


Friday, June 2, 2023

Power Query - Valida Preenchimento em Colunas

 = Table.TransformColumns(#"Added Custom1", {

{ "1", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "2", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "3", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "4", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "5", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "6", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "7", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "8", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "9", each if _ <> "" then 1 else 0, Int64.Type}, 

{ "10", each if _ <> "" then 1 else 0, Int64.Type},

{ "11", each if _ <> "" then 1 else 0, Int64.Type},

{ "12", each if _ <> "" then 1 else 0, Int64.Type},

{ "13", each if _ <> "" then 1 else 0, Int64.Type},

{ "14", each if _ <> "" then 1 else 0, Int64.Type},

{ "15", each if _ <> "" then 1 else 0, Int64.Type},

{ "16", each if _ <> "" then 1 else 0, Int64.Type},

{ "17", each if _ <> "" then 1 else 0, Int64.Type},

{ "18", each if _ <> "" then 1 else 0, Int64.Type},

{ "19", each if _ <> "" then 1 else 0, Int64.Type},

{ "20", each if _ <> "" then 1 else 0, Int64.Type},

{ "21", each if _ <> "" then 1 else 0, Int64.Type},

{ "22", each if _ <> "" then 1 else 0, Int64.Type},

{ "23", each if _ <> "" then 1 else 0, Int64.Type},

{ "24", each if _ <> "" then 1 else 0, Int64.Type},

{ "25", each if _ <> "" then 1 else 0, Int64.Type},

{ "26", each if _ <> "" then 1 else 0, Int64.Type},

{ "27", each if _ <> "" then 1 else 0, Int64.Type},

{ "28", each if _ <> "" then 1 else 0, Int64.Type},

{ "29", each if _ <> "" then 1 else 0, Int64.Type},

{ "30", each if _ <> "" then 1 else 0, Int64.Type},

{ "31", each if _ <> "" then 1 else 0, Int64.Type},

{ "32", each if _ <> "" then 1 else 0, Int64.Type},

{ "33", each if _ <> "" then 1 else 0, Int64.Type},

{ "34", each if _ <> "" then 1 else 0, Int64.Type},

{ "35", each if _ <> "" then 1 else 0, Int64.Type},

{ "36", each if _ <> "" then 1 else 0, Int64.Type},

{ "37", each if _ <> "" then 1 else 0, Int64.Type},

{ "38", each if _ <> "" then 1 else 0, Int64.Type},

{ "39", each if _ <> "" then 1 else 0, Int64.Type},

{ "40", each if _ <> "" then 1 else 0, Int64.Type},

{ "41", each if _ <> "" then 1 else 0, Int64.Type},

{ "42", each if _ <> "" then 1 else 0, Int64.Type},

{ "43", each if _ <> "" then 1 else 0, Int64.Type},

{ "44", each if _ <> "" then 1 else 0, Int64.Type},

{ "45", each if _ <> "" then 1 else 0, Int64.Type},

{ "46", each if _ <> "" then 1 else 0, Int64.Type},

{ "47", each if _ <> "" then 1 else 0, Int64.Type},

{ "48", each if _ <> "" then 1 else 0, Int64.Type},

{ "49", each if _ <> "" then 1 else 0, Int64.Type},

{ "50", each if _ <> "" then 1 else 0, Int64.Type},

{ "51", each if _ <> "" then 1 else 0, Int64.Type},

{ "52", each if _ <> "" then 1 else 0, Int64.Type}


    })

Sunday, April 30, 2023

DAX - Sample RLS

After create rules:

https://learn.microsoft.com/en-us/power-bi/enterprise/service-admin-rls

dataset_RLS:

[Email] =  userprincipalname() 

or

[Email] =  USERNAME() 

Por exemplo, se o nome de usuário completo de um usuário for "jane.doe@contoso.com", a função USERNAME() retornaria apenas "jane.doe", enquanto a função USERPRINCIPALNAME() retornaria "jane.doe@contoso.com".

Em resumo, a função USERNAME() é útil quando você precisa apenas do nome de usuário sem o domínio, enquanto a função USERPRINCIPALNAME() é útil quando você precisa do identificador exclusivo do usuário.


DIM_Reunioes_Plan:

[SME] = LOOKUPVALUE(dataset_RLS[SME],dataset_RLS[Email],userprincipalname())

Wednesday, April 19, 2023

Power Query - Read DB Access and accdb files

 let

    Source = 

    //Access.Database(File.Contents("C:\Users\biprio\PRIO ENERGY SA(1)\W Analytics - BigData\datasets\SPANCOP\APOfiles\prio-truck prg.accdb"), [CreateNavigationProperties=true])

    OleDb.DataSource("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""C:\temp\FILE.accdb"";Jet OLEDB:Database Password="""";", [Query="SELECT * FROM TABLE "]),

    #"Removed Columns" = Table.RemoveColumns(Source,{"CDESCR"}),

    #"Filtered Rows" = Table.SelectRows(#"Removed Columns", each [NIF] <> null and [NIF] <> "")

in

    #"Filtered Rows"

Thursday, April 13, 2023

PBIX - DAX - Combine Hibrid Years Recursive

 


Configuração via Power Query:

-----------------------------------------------------------
1 - Criar Parameter Anos

"2022,2023" meta [IsParameterQuery=true, List={"Diario", "2018", "2019", "2020", "2018,2019,2020", "2021"}, DefaultValue="Diario", Type="Text", IsParameterQueryRequired=true]

-----------------------------------------------------------
2 - Criar Função que fará chamada recursiva

let
    Source = (ano) => let 
    
        EmptyTable = #table({"CALDAY", "DOC_CURRCY", "SALES_UNIT", "CUST_SALES", "ZMATERIAL", "DISTR_CHAN", "DIVISION", "SALESORG", "PLANT", "DOC_TYPE", "ZWS_PAYMD", "DOC_CATEG", "HH", "ZWS_SUBTP", "ZWS_SBPAY", ".NIF_Venda", "ZOPERADOR", "ZCARDNUM1", "GROSS_VAL", "TAX_VALUE", "CML_OR_QTY", "NET_VALUE"}, {}),

        Source = PowerBI.Dataflows(null),
        Workspace = Source{[workspaceId="786887ff-e45d-4d89-b874-b99d907cd9c3"]}[Data],

        Dataflow = Workspace{[dataflowName=Text.Combine({"Prio_BW_DF_Vendas_", ano})]}[Data],

        #"Removed Other Columns" = Table.SelectColumns(Dataflow,{"Data"}),
        #"Expanded Data" = Table.ExpandTableColumn(#"Removed Other Columns", "Data", 
{"CALDAY", "DOC_CURRCY", "SALES_UNIT", "CUST_SALES", "ZMATERIAL", "DISTR_CHAN", "DIVISION", "SALESORG", "PLANT", "DOC_TYPE", "ZWS_PAYMD", "DOC_CATEG", "HH", "ZWS_SUBTP", "ZWS_SBPAY", ".NIF_Venda", "ZOPERADOR", "ZCARDNUM1", "GROSS_VAL", "TAX_VALUE", "CML_OR_QTY", "NET_VALUE"}, 
{"CALDAY", "DOC_CURRCY", "SALES_UNIT", "CUST_SALES", "ZMATERIAL", "DISTR_CHAN", "DIVISION", "SALESORG", "PLANT", "DOC_TYPE", "ZWS_PAYMD", "DOC_CATEG", "HH", "ZWS_SUBTP", "ZWS_SBPAY", ".NIF_Venda", "ZOPERADOR", "ZCARDNUM1", "GROSS_VAL", "TAX_VALUE", "CML_OR_QTY", "NET_VALUE"}),

        Final_Table = try #"Expanded Data" otherwise EmptyTable
        
    in 
        Final_Table
in
    Source


-----------------------------------------------------------
3 - Criar TABLE:

let
    Parameters = Text.Split(Anos, ","),
    ParameterTable = Table.FromList(Parameters, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Renamed Columns" = Table.RenameColumns(ParameterTable,{{"Column1", "Ano"}}),
    TableList = Table.AddColumn(#"Renamed Columns", "Tables", each Get_FAT_Vendas([Ano])),

    CombinedTables = Table.Combine(TableList[Tables])
in
    CombinedTables
-----------------------------------------------------------

Wednesday, March 29, 2023

DAX - Comparação de informações entre 2 tabelas (PROCV)

.Vlr_PF_Diff =

CALCULATE ( SUMX ( Table01, Table01[Valor_Compara01] - CALCULATE ( SUMX ( RELATEDTABLE ( Table02 ), (Table02[Valor_Compara02] )), FILTER ( Table02 , AND(Table02[Var_A] = Table01[Var_A], AND(Table02[Var_B] = Table01[Var_B] , Table02[Var_C] = Table01[Var_C] )) ) ) ) )

Wednesday, March 22, 2023

Postgres SQL - AWS Connect

 To disable encryption

  1. File --> Options and settings --> Data source settings
  2. Click Edit Permissions on your connection
  3. Uncheck Encrypt Connections
==================================================

Power Query:
let
    Source = Value.NativeQuery(PostgreSQL.Database("database.XPTO.com.br", "DBName", [CreateNavigationProperties=false]),
"select#(lf)  table_name,#(lf)  pg_size_pretty(pg_relation_size(quote_ident(table_name))),#(lf)  pg_relation_size(quote_ident(table_name))#(lf)from information_schema.tables#(lf)where table_schema = 'public'#(lf)order by 3 desc", null, [EnableFolding=true])
in
    Source


=============================
select
  table_name,
  pg_size_pretty(pg_relation_size(quote_ident(table_name))),
  pg_relation_size(quote_ident(table_name))
from information_schema.tables
where table_schema = 'public'
order by 3 desc;

select table_schema, table_name, pg_relation_size('"'||table_schema||'"."'||table_name||'"')
from information_schema.tables
order by 3

DAX - Running total based on ranking index - Acumulado Ranking

Rank = 


RANKX (

    SUMMARIZE (

        ALLSELECTED ( FAT_TABLE ),

        FAT_TABLE[YYYYMM],

        FAT_TABLE[VAR1]

    ),

    CALCULATE ( SUM ( FAT_TABLE[Price (€/t)] ) ),

    ,

    ASC,

    DENSE

)

=============================================== 


Running VAR_Sum = 

IF (

    ISINSCOPE ( FAT_TABLE[VAR1] ) && ISINSCOPE ( FAT_TABLE[YYYYMM] ),

    VAR CurrentRank = [Rank]

    VAR SummarizeFAT_TABLE =

        CALCULATETABLE (

            SUMMARIZE ( FAT_TABLE, FAT_TABLE[VAR1], FAT_TABLE[YYYYMM] ),

            ALLSELECTED ( FAT_TABLE )

        )

    VAR FAT_TABLESales =

        ADDCOLUMNS ( SummarizeFAT_TABLE, "@TotalSum", [VAR_Sum], "@Rank", [Rank] )

    VAR Result =

        SUMX ( FILTER ( FAT_TABLESales, [@Rank] <= CurrentRank ), [@TotalSum] )

    RETURN

        Result

)

=============================================== 


Monday, February 27, 2023

Power Query - Convert 18-digit LDAP/FILETIME timestamps

 Convert 18-digit LDAP/FILETIME timestamps


Power Query:

  #"Added custom" = Table.TransformColumnTypes(Table.AddColumn(#"Replaced Value9", ".DateLastLogon", each [lastLogon] / 864000000000), {{".DateLastLogon", type datetime}}),

  #"Added custom2" = Table.TransformColumnTypes(Table.AddColumn(#"Added custom", ".DateLastLogonTimestamp", each [lastLogonTimestamp] / 864000000000), {{".DateLastLogonTimestamp", type datetime}}),

  #"Added custom3" = Table.TransformColumnTypes(Table.AddColumn(#"Added custom2", ".DateAccountExpires", each [accountExpires] / 864000000000), {{".DateAccountExpires", type datetime}}),

  

Font help me:

https://www.epochconverter.com/ldap




864000000000

80589246768


20000000000

1676040067

Tuesday, February 7, 2023

Power BI - Motor de Alarmisticas via Visual Table (Python Azure DAX PBIX)

 Step by step para buscar dados de dentro de um Visual Table 

  1. Criar PBIX e gerar a tabela com as informações minimas ( 

    E-mail 
    1. Valor a Monitorar 
    2. Valor Range In 
    3. Valor Range out) 
  2. Gerar query via PBIX 
  3. Executar/Testar query via DaxStudio 
  4. Ajustar query JSON para execução REST API  
    1. Replace:  " por \"  
  5. Testar query via REST API 
 

 

 

 

 

ID 

Descrição 

1 

 

2 

 

 

3 

 

4 

{ 

  "queries": [ 

    { 

      "query":  

" 

DEFINE 

  VAR __DS0Core =  

    SUMMARIZECOLUMNS( 

      ROLLUPADDISSUBTOTAL( 

        ROLLUPGROUP('DIM_Alarmes'[Email], 'DIM_Alarmes'[Status]), \"IsGrandTotalRowTotal\" 

      ), 

      \"v_Valores\", 'DIM_Alarmes'[.Valores], 

      \"v_qtdRegs\", 'DIM_Alarmes'[.qtdRegs] 

    ) 

  

  VAR __DS0PrimaryWindowed =  

    TOPN(502, __DS0Core, [IsGrandTotalRowTotal], 0, 'DIM_Alarmes'[Status], 0, 'DIM_Alarmes'[Email], 1) 

  

EVALUATE 

  __DS0PrimaryWindowed 

  

ORDER BY 

  [IsGrandTotalRowTotal] DESC, 'DIM_Alarmes'[Status] DESC, 'DIM_Alarmes'[Email]    

" 

    } 

  ], 

  "serializerSettings": { 

    "includeNulls": true 

  } 

  

} 

5 

6 

 

 

 

 

 

 

 

 

 

 

SQL - Query Analytics Basic

  SELECT Nome_Produto, ROUND(MIN(Valor_Venda), 2) AS Valor_Minimo, ROUND(MAX(Valor_Venda), 2) AS Valor_Maximo, ROUND(AV...