Monday 26 June 2017

Movendo Média Ssas


A maioria das pessoas está familiarizada com a frase, isso vai matar dois pássaros com uma pedra. Se você não estiver, a fase se refere a uma abordagem que aborda dois objetivos em uma ação. (Infelizmente, a expressão em si é bastante desagradável, como a maioria de nós não queremos atirar pedras em animais inocentes) Hoje I39m vai cobrir algumas noções básicas sobre dois grandes recursos no SQL Server: o índice Columnstore (disponível somente no SQL Server Enterprise) e O SQL Query Store. A Microsoft implementou o índice Columnstore no SQL 2012 Enterprise, embora o tenha aprimorado nas últimas duas versões do SQL Server. A Microsoft lançou o Query Store no SQL Server 2016. Então, quais são esses recursos e por que eles são importantes? Bem, eu tenho uma demo que apresentará os dois recursos e mostrar como eles podem nos ajudar. Antes de eu ir mais longe, eu também cobrir este (e outros recursos SQL 2016) no meu artigo revista CODE sobre novos recursos SQL 2016. Como uma introdução básica, o índice Columnstore pode ajudar a acelerar as consultas que scanaggregate sobre grandes quantidades de dados e O Query Store controla as execuções de consultas, os planos de execução e as estatísticas de tempo de execução que você normalmente precisa coletar manualmente. Confie em mim quando eu digo, estas são grandes características. Para esta demonstração, usarei o banco de dados de demonstração do Microsoft Contoso Retail Data Warehouse. Falando francamente, Contoso DW é como quota realmente grande AdventureWorksquot, com tabelas contendo milhões de linhas. (A maior tabela AdventureWorks contém aproximadamente 100.000 linhas no máximo). Você pode baixar o banco de dados Contoso DW aqui: microsoften-usdownloaddetails. aspxid18279. Contoso DW funciona muito bem quando você quer testar o desempenho em consultas contra tabelas maiores. O Contoso DW contém uma tabela de fatos de data warehouse padrão chamada FactOnLineSales, com 12,6 milhões de linhas. Isso certamente não é a maior tabela de data warehouse do mundo, mas também não é uma criança. Suponha que eu quero resumir o montante das vendas de produtos para 2009 e classificar os produtos. Eu poderia consultar a tabela de fatos e juntar-se à tabela de dimensão do produto e usar uma função RANK, assim: Aqui há um conjunto de resultados parciais das 10 linhas superiores, por Vendas totais. No meu laptop (i7, 16 GB de RAM), a consulta leva em qualquer lugar 3-4 segundos para ser executado. Isso pode não parecer o fim do mundo, mas alguns usuários podem esperar resultados quase instantâneos (da maneira que você pode ver resultados quase instantâneos ao usar o Excel contra um cubo OLAP). O único índice que eu tenho atualmente nesta tabela é um índice agrupado em uma chave de vendas. Se eu olhar para o plano de execução, o SQL Server faz uma sugestão para adicionar um índice de cobertura para a tabela: Agora, apenas porque o SQL Server sugere um índice, doesn39t significa que você deve cegamente criar índices em cada quotmissing indexquot mensagem. No entanto, nesta instância, o SQL Server detecta que estamos a filtrar com base no ano e utilizando a chave de produto eo montante de vendas. Assim, o SQL Server sugere um índice de cobertura, com o DateKey como o campo de chave de índice. A razão pela qual chamamos isso de índice de quotcoveringquot é porque o SQL Server irá quotbring ao longo dos campos não-chave que usamos na consulta, quotfor o ridequot. Dessa forma, o SQL Server não precisa usar a tabela ou o índice em cluster em todo o mecanismo de banco de dados pode simplesmente usar o índice de cobertura para a consulta. Os índices de cobertura são populares em determinados cenários de armazenamento de dados e de banco de dados de relatórios, embora tenham um custo de manutenção do mecanismo de banco de dados. Nota: Os índices de cobertura têm sido em torno de um longo tempo, por isso eu haven39t ainda cobriu o índice Columnstore eo Query Store. Então, vou adicionar o índice de cobertura: Se eu re-executar a mesma consulta que eu corri há um momento (aquela que agregou o valor de vendas para cada produto), a consulta às vezes parece correr cerca de um segundo mais rápido, e eu recebo um Plano de execução diferente, que usa um Index Seek em vez de um Index Scan (usando a chave de data no índice de cobertura para recuperar as vendas para 2009). Assim, antes do índice Columnstore, esta poderia ser uma forma de optimizar esta consulta em versões mais antigas do SQL Server. Ele é executado um pouco mais rápido do que o primeiro, e eu recebo um plano de execução com um Index Seek em vez de um Index Scan. No entanto, existem alguns problemas: Os dois operadores de execução quotIndex Seekquot e quotHash Match (Aggregate) quot ambos essencialmente operam quotrow por rowquot. Imagine isso em uma tabela com centenas de milhões de linhas. Relacionado, pense sobre o conteúdo de uma tabela de fatos: neste caso, um único valor de chave de data e um único valor de chave de produto podem ser repetidos em centenas de milhares de linhas (lembre-se, a tabela de fatos também tem chaves para geografia, promoção, vendedor , Etc.) Assim, quando o quotIndex Seekquot e o quotHash Matchquot trabalham linha por linha, eles estão fazendo isso sobre valores que podem ser repetidos em muitas outras linhas. Isso é normalmente onde I39d segue para o SQL Server Columnstore índice, que oferece um cenário para melhorar o desempenho desta consulta de maneiras surpreendentes. Mas antes de eu fazer isso, vamos voltar no tempo. Vamos voltar ao ano de 2010, quando a Microsoft introduziu um add-in para o Excel conhecido como PowerPivot. Muitas pessoas provavelmente se lembram de ver demonstrações do PowerPivot para Excel, onde um usuário poderia ler milhões de linhas de uma fonte de dados externa para o Excel. O PowerPivot comprimiria os dados e forneceria um mecanismo para criar tabelas dinâmicas e gráficos dinâmicos que funcionassem a velocidades incríveis em relação aos dados compactados. O PowerPivot usou uma tecnologia em memória que a Microsoft denominou quotVertiPaqquot. Essa tecnologia em memória do PowerPivot basicamente levaria valores de chave de negócios duplicados e os comprimia para um único vetor. A tecnologia em memória também digitalizaria esses valores em paralelo, em blocos de várias centenas de cada vez. A linha de fundo é que a Microsoft assou uma grande quantidade de aprimoramentos de desempenho no recurso VertiPaq em memória para usarmos, logo depois da caixa proverbial. Porque estou fazendo exame deste passeio pequeno para baixo a pista da memória Porque no SQL Server 2012, Microsoft executou um dos recursos os mais importantes no history de seu motor do banco de dados: o índice do Columnstore. O índice é realmente um índice somente no nome: é uma maneira de tomar uma tabela do SQL Server e criar um columnstore compactado na memória que comprime valores de chave estrangeira duplicados para valores de vetor simples. A Microsoft também criou um novo pool de buffer para ler esses valores vetoriais compactados em paralelo, criando o potencial para ganhos de desempenho enormes. Assim, I39m vai criar um índice columnstore na tabela, e I39ll ver quanto melhor (e mais eficientemente) a consulta é executado, versus a consulta que é executado contra o índice de cobertura. Então, eu criarei uma cópia duplicada de FactOnlineSales (I39ll chamá-lo de FactOnlineSalesDetailNCCS), e I39ll criará um índice columnstore na tabela duplicada dessa maneira eu won39t interferir com a tabela original eo índice de cobertura de qualquer maneira. Em seguida, I39ll criar um índice columnstore na nova tabela: Observe várias coisas: I39ve especificado várias colunas de chave estrangeira, bem como o montante de vendas. Lembre-se de que um índice columnstore não é como um índice tradicional de armazenamento em fila. Não há quotkeyquot. Estamos simplesmente indicando quais colunas SQL Server deve compactar e colocar em um columnstore in-memory. Para usar a analogia do PowerPivot para Excel quando criamos um índice columnstore, estamos dizendo ao SQL Server que faça essencialmente a mesma coisa que o PowerPivot fez quando importamos 20 milhões de linhas para o Excel usando o PowerPivot. Então, I39ll re-executa a consulta, desta vez usando A tabela duplicada FactOnlineSalesDetailNCCS que contém o índice columnstore. Esta consulta é executada instantaneamente em menos de um segundo. E eu também posso dizer que mesmo que a mesa tivesse centenas de milhões de linhas, ela ainda funcionaria com o proverbial quotbat de um cílio. Podemos olhar para o plano de execução (e em alguns momentos, vamos), mas agora é hora de cobrir o recurso Query Store. Imagine por um momento que executamos ambas as consultas durante a noite: a consulta que usou a tabela regular de FactOnlineSales (com o índice de cobertura) e, em seguida, a consulta que usou a tabela duplicada com o índice Columnstore. Quando iniciamos a sessão na manhã seguinte, gostaríamos de ver o plano de execução para ambas as consultas à medida que elas ocorreram, assim como as estatísticas de execução. Em outras palavras, gostaríamos de ver as mesmas estatísticas que seríamos capazes de ver se executamos ambas as consultas interativamente no SQL Management Studio, transformadas em TIME e IO Statistics e visualizamos o plano de execução logo após a execução da consulta. Bem, isso é o que o Query Store nos permite fazer, podemos ativar (habilitar) o Query Store para um banco de dados, que acionará o SQL Server para armazenar a execução da consulta e planejar as estatísticas para que possamos visualizá-las mais tarde. Então, I39m vai habilitar o Query Store no banco de dados Contoso com o seguinte comando (e I39ll também limpar qualquer cache): Então I39ll executar as duas consultas (e quotpretendquot que eu os corri há horas): Agora vamos fingir que correram horas atrás. De acordo com o que eu disse, o Query Store irá capturar as estatísticas de execução. Então, como posso vê-los Felizmente, isso é muito fácil. Se eu expandir o banco de dados Contoso DW, ver uma pasta Query Store. O Query Store tem uma enorme funcionalidade e I39ll tentar cobrir grande parte dela em postagens de blog subseqüentes. Mas para agora, eu quero ver as estatísticas de execução sobre as duas consultas e examinar especificamente os operadores de execução para o índice columnstore. Então, clique com o botão direito do mouse no Top Resource Consuming Queries e execute essa opção. Isso me dá um gráfico como o abaixo, onde eu posso ver o tempo de duração da execução (em milissegundos) para todas as consultas que foram executadas. Nesse caso, a Consulta 1 era a consulta contra a tabela original com o índice de cobertura e a Consulta 2 estava contra a tabela com o índice columnstore. Os números não são o índice columnstore superou o índice tablecovering original por um fator de quase 7 para 1. Eu posso mudar a métrica para olhar para o consumo de memória em vez disso. Nesse caso, observe que a consulta 2 (a consulta de índice columnstore) usou muito mais memória. Isso demonstra claramente por que o índice columnstore representa a tecnologia quotin-memoryquot O SQL Server carrega todo o índice columnstore na memória e usa um pool de buffer completamente diferente com operadores de execução aprimorados para processar o índice. OK, então temos alguns gráficos para ver as estatísticas de execução podemos ver o plano de execução (e operadores de execução) associados a cada execução Sim, nós podemos Se você clicar na barra vertical para a consulta que usou o índice columnstore, você verá a execução Abaixo. A primeira coisa que vemos é que o SQL Server executou uma varredura de índice columnstore, e que representou quase 100 do custo da consulta. Você pôde dizer, quotWait um minuto, a primeira consulta usou um índice de coberta e executou um índice procura assim que como pode uma varredura do índice do columnstore ser mais rápida que uma pergunta legitimate, e felizmente there39s uma resposta. Mesmo quando a primeira consulta executou um index seek, ela ainda executou quotrow por rowquot. Se eu colocar o mouse sobre o operador de varredura de índice columnstore, eu vejo uma dica de ferramenta (como a abaixo), com uma configuração importante: o Modo de Execução é BATCH (em oposição a ROW.), Que é o que tínhamos com a primeira consulta usando o Índice de cobertura). Esse modo BATCH informa-nos que o SQL Server está processando os vetores compactados (para quaisquer valores de chave externa duplicados, como a chave do produto e a chave de data) em lotes de quase 1.000, em paralelo. Assim, o SQL Server ainda é capaz de processar o índice columnstore muito mais eficientemente. Além disso, se eu colocar o mouse sobre a tarefa Hash Match (Aggregate), também vejo que o SQL Server está agregando o índice columnstore usando o modo Batch (embora o próprio operador represente uma pequena porcentagem do custo da consulta) SQL Server comprime os valores nos dados, trata os valores como vetores, e lê-los em blocos de quase mil valores em paralelo, mas a minha consulta só queria dados para 2009. Assim é o SQL Server digitalização sobre o Conjunto de dados Uma vez mais, uma boa pergunta. A resposta é, quotNot reallyquot. Felizmente para nós, o novo pool de buffer de índice columnstore executa outra função chamada quotsegment eliminationquot. Basicamente, o SQL Server examinará os valores de vetor para a coluna de chave de data no índice columnstore e eliminará os segmentos que estão fora do escopo do ano 2009. I39ll parar aqui. Em postagens subseqüentes, o I39ll cobre o índice columnstore eo Query Store com mais detalhes. Essencialmente, o que vimos aqui hoje é que o índice Columnstore pode acelerar significativamente as consultas que scanaggregate sobre grandes quantidades de dados eo Query Store irá capturar execuções de consulta e nos permitir examinar as estatísticas de execução e desempenho mais tarde. No final, gostaríamos de produzir um conjunto de resultados que mostre o seguinte. Observe três coisas: As colunas essencialmente pivô todas as Razões de retorno possíveis, depois de mostrar o valor de vendas O conjunto de resultados contém um total de subtotais pela semana (domingo) data em todos os clientes (onde o cliente é NULL) Linha (onde o cliente ea data são ambos NULL) Primeiro, antes de eu entrar no final do SQL, poderíamos usar a capacidade dinâmica de pivotmatrix no SSRS. Simplesmente precisaríamos combinar os dois conjuntos de resultados por uma coluna e então poderíamos alimentar os resultados para o controle de matriz SSRS, que irá espalhar as razões de retorno através do eixo colunas do relatório. No entanto, nem todos usam SSRS (embora a maioria das pessoas deve). Mas mesmo assim, às vezes os desenvolvedores precisam consumir conjuntos de resultados em algo que não seja uma ferramenta de geração de relatórios. Assim, para este exemplo, vamos assumir que queremos gerar o conjunto de resultados para uma página de grade da web e, possivelmente, o desenvolvedor quer quotstrip outquot as linhas subtotal (onde eu tenho um ResultSetNum valor de 2 e 3) e colocá-los em uma grade de resumo. Então, linha de fundo, precisamos gerar a saída acima diretamente de um procedimento armazenado. E como uma torção adicionada na próxima semana poderia haver Return Reason X e Y e Z. Então nós don39t saber quantas razões de retorno poderia haver. Nós simples queremos que a consulta pivote sobre os possíveis valores distintos para a razão de retorno. Aqui é onde o T-SQL PIVOT tem uma restrição que precisamos para fornecer-lhe os valores possíveis. Como não sabemos que até o tempo de execução, precisamos gerar a seqüência de consulta dinamicamente usando o padrão SQL dinâmico. O padrão SQL dinâmico envolve gerar a sintaxe, peça por peça, armazená-lo em uma seqüência de caracteres e, em seguida, executar a seqüência de caracteres no final. SQL dinâmico pode ser complicado, pois temos de incorporar sintaxe dentro de uma seqüência de caracteres. Mas, neste caso, é nossa única opção verdadeira se quisermos lidar com um número variável de razões de retorno. Sempre achei que a melhor maneira de criar uma solução SQL dinâmica é descobrir o quotidealquot gerado-consulta seria no final (neste caso, dadas as razões de retorno que sabemos sobre) e, em seguida, engenharia reversa-lo por piecing Juntos uma parte de cada vez. E assim, aqui está o SQL que precisamos se soubéssemos que as razões de retorno (de A a D) eram estáticas e não mudariam. A consulta faz o seguinte: Combina os dados de SalesData com os dados de ReturnData, onde nós quothard-wirequot a palavra Sales como um tipo de ação forma a tabela de vendas e, em seguida, use a razão de retorno dos dados de retorno na mesma coluna ActionType. Isso nos dará uma coluna de ActionType limpa na qual girar. Estamos combinando as duas instruções SELECT em uma expressão de tabela comum (CTE), que é basicamente uma subconsulta de tabela derivada que usamos posteriormente na próxima instrução (para PIVOT) Uma declaração PIVOT contra o CTE, que somar os dólares para o Action Type Estar em um dos possíveis valores do Tipo de Ação. Observe que este não é o conjunto de resultados final. Estamos colocando isso em um CTE que lê a partir do primeiro CTE. A razão para isso é porque nós queremos fazer vários agrupamentos no final. A instrução SELECT final, que lê a partir do PIVOTCTE e combina com uma consulta subseqüente contra o mesmo PIVOTCTE, mas onde também implementar dois agrupamentos no recurso GROUPING SETS em SQL 2008: GRUPO pela data de fim de semana (dbo. WeekEndingDate) GRUPO para todas as linhas () Então, se soubéssemos com certeza que nunca teríamos mais códigos de razão de retorno, então essa seria a solução. No entanto, precisamos considerar outros códigos de razão. Portanto, precisamos gerar essa consulta inteira acima como uma grande seqüência onde construímos as possíveis razões de retorno como uma lista separada por vírgulas. I39m vai mostrar todo o código T-SQL para gerar (e executar) a consulta desejada. E então eu dividi-lo em partes e explicar cada passo. Então primeiro, aqui está o código inteiro para gerar dinamicamente o que eu tenho acima. Existem basicamente cinco etapas que precisamos cobrir. Passo 1 . Nós sabemos que em algum lugar na mistura, precisamos gerar uma seqüência de caracteres para isso na consulta: SalesAmount, razão A, razão B, razão C, razão D0160016001600160 O que podemos fazer é construído uma expressão de tabela comum temporária que combina o hard wired quotSales Coluna de quantidade com a lista exclusiva de possíveis códigos de razão. Uma vez que temos que em um CTE, podemos usar o pequeno truque de FOR XML PATH (3939) para recolher essas linhas em uma única seqüência de caracteres, coloque uma vírgula em frente de cada linha que a consulta lê e, em seguida, use STUFF para substituir A primeira instância de uma vírgula com um espaço vazio. Este é um truque que você pode encontrar em centenas de blogs SQL. Então, esta primeira parte constrói uma string chamada ActionString que podemos usar mais abaixo. Passo 2 . Também sabemos que we39ll quer somar as colunas de razão geradas geradas, juntamente com a coluna de vendas padrão. Portanto, precisamos de uma string separada para isso, que eu chamo SUMSTRING. I39ll simplesmente usar o ActionString original e, em seguida, substituir os colchetes externos com sintaxe SUM, mais os suportes originais. Passo 3: Agora começa o verdadeiro trabalho. Usando essa consulta original como modelo, queremos gerar a consulta original (começando com o UNION das duas tabelas), mas substituindo quaisquer referências a colunas articuladas com as strings geradas dinamicamente acima. Além disso, embora não seja absolutamente necessário, também criei uma variável para simplesmente qualquer combinação de feed de retorno de carro que desejamos incorporar na consulta gerada (para legibilidade). Então we39ll construir toda a consulta em uma variável chamada SQLPivotQuery. Passo 4. Continuamos construindo a consulta novamente, concatenando a sintaxe que podemos quothard-wire com o ActionSelectString (que geramos dinamicamente para manter todos os possíveis valores de razão de retorno) Passo 5. Finalmente, we39ll gera a parte final da Pivot Query, que lê a partir da 2ª expressão de tabela comum (PIVOTCTE, a partir do modelo acima) e gera o SELECT final para ler a partir do PIVOTCTE e combiná-lo com uma 2ª leitura contra PIVOTCTE para Implementar os conjuntos de agrupamento. Finalmente, nós podemos quotexecutequot a seqüência usando o sistema SQL armazenado proc spexecuteSQL Então espero que você pode ver que o processo para seguir para este tipo de esforço é Determine qual seria a consulta final, com base em seu conjunto atual de dados e valores Um modelo de consulta) Escreva o código T-SQL necessário para gerar esse modelo de consulta como uma string. Posivelmente, a parte mais importante é determinar o conjunto único de valores em que você PIVOT e, em seguida, colapso-los em uma Cadeia de caracteres usando a função STUFF eo truque FOR XML PATH (3939) Então, o que está na minha mente hoje Bem, pelo menos 13 itens Dois Eu escrevi um projecto de BDR que se concentrou (em parte) sobre o papel da educação e do valor de um bom fundo de artes liberais não apenas para a indústria de software, mas mesmo para outras indústrias também. Um dos temas deste particular BDR enfatizou um ponto de vista fundamental e esclarecido do renomado arquiteto de software Allen Holub sobre as artes liberais. Parafraseando fielmente a sua mensagem: destacou os paralelos entre a programação e o estudo da história, lembrando a todos que a história é leitura e escrita (e acrescentam, identificando padrões), eo desenvolvimento de software também é leitura e escrita (e, novamente, identificação de padrões ). E assim eu escrevi um pedaço de opinião que focalizou isto e outros tópicos relacionados. Mas até hoje, eu nunca cheguei perto de publicá-lo. De vez em quando eu penso em revisá-lo, e eu até me sento por alguns minutos e faço alguns ajustes. Mas então a vida em geral iria ficar no caminho e Id nunca terminá-lo. Então, o que mudou Algumas semanas atrás, o colunista CoDe Magazine e o líder da indústria, Ted Neward, escreveram um artigo em sua coluna regular, Managed Coder, que chamou minha atenção. O título do artigo é On Liberal Arts. E eu recomendo que todos lê-lo. Ted discute o valor de um fundo de artes liberais, a falsa dicotomia entre um fundo de artes liberais e sucesso no desenvolvimento de software, ea necessidade de escrever bem. Ele fala sobre alguns de seus próprios encontros anteriores com o gerenciamento de pessoal de RH em relação a sua formação educacional. Ele também enfatiza a necessidade de aceitar e se adaptar às mudanças em nosso setor, bem como as características de um profissional de software bem-sucedido (ser confiável, planejar com antecedência e aprender a superar o conflito inicial com outros membros da equipe). Portanto, é uma ótima leitura, como são Teds outros CoDe artigos e entradas de blog. Também me fez voltar a pensar sobre minhas opiniões sobre este (e outros tópicos) também, e finalmente me motivou a terminar meu próprio editorial. Então, melhor tarde do que nunca, aqui estão os meus atuais Bakers Dúzia de Reflexões: Eu tenho um ditado: A água congela em 32 graus. Se você está em um papel de formação, você pode pensar que você está fazendo tudo no mundo para ajudar alguém quando na verdade, theyre apenas sentindo uma temperatura de 34 graus e, portanto, as coisas arent solidificação para eles. Às vezes leva apenas um pouco mais de esforço ou outro catalizador ideachemical ou uma nova perspectiva que significa que aqueles com educação prévia pode recorrer a diferentes fontes. A água congela a 32 graus. Algumas pessoas podem manter altos níveis de concentração, mesmo com um quarto cheio de pessoas barulhentas. Eu não sou um deles ocasionalmente eu preciso de alguma privacidade para pensar através de uma questão crítica. Algumas pessoas descrevem isso como você tem que aprender a andar longe dele. Dito de outra forma, é uma busca pelo ar rarefeito. Na semana passada eu passei horas em um quarto semi-iluminado e quieto com um quadro branco, até que compreendi um problema completamente. Foi só então que eu poderia ir falar com outros desenvolvedores sobre uma solução. A mensagem aqui não é para pregar como você deve ir sobre o seu negócio de resolver problemas, mas sim para todos saberem os seus pontos fortes eo que funciona, e usá-los para sua vantagem, tanto quanto possível. Algumas frases são como unhas no quadro-negro para mim. Use-o como um momento de ensino é um. (Por que é como unhas em um quadro-negro Porque se você estiver em um papel de mentor, você deve normalmente estar no modo de momento de ensino de qualquer maneira, no entanto sutilmente). Heres outro eu não posso realmente explicar isto nas palavras, mas eu compreendo-o. Isso pode soar um pouco frio, mas se uma pessoa realmente não pode explicar alguma coisa em palavras, talvez eles não entendem. Claro, uma pessoa pode ter uma sensação fuzzy de como funciona algo Eu posso blefar meu caminho através de descrever como funciona uma câmera digital, mas a verdade é que eu realmente não entendo tudo isso bem. Existe um campo de estudo conhecido como epistemologia (o estudo do conhecimento). Uma das bases fundamentais para entender se é uma câmera ou um padrão de design - é a capacidade de estabelecer contexto, identificar a cadeia de eventos relacionados, os atributos de quaisquer componentes ao longo do caminho, etc Sim, a compreensão é por vezes muito trabalho árduo , Mas mergulhar em um tópico e quebrá-lo aparte vale a pena o esforço. Mesmo aqueles que evitam a certificação reconhecerá que o processo de estudar para os testes de certificação ajudará a preencher lacunas no conhecimento. Um gerente de banco de dados é mais provável contratar um desenvolvedor de banco de dados que pode falar extemporaneamente (e sem esforço) sobre níveis de isolamento de transação e acionadores, em oposição a alguém que tipo de sabe sobre ele, mas luta para descrever o seu uso. Há outro corolário aqui. Ted Neward recomenda que os desenvolvedores ocupam falar em público, blogs, etc Concordo 100. O processo de falar em público e blogs vai praticamente obrigá-lo a começar a pensar sobre os temas e quebrar as definições que você pode ter tomado por certo. Alguns anos atrás, eu pensei que eu entendia a declaração T-SQL MERGE muito bem. Mas só depois de escrever sobre isso, falando, colocando questões de outros que tinham perspectivas que nunca me ocorreu que o meu nível de compreensão aumentou exponencialmente. Eu conheço uma história de um gerente de contratação que uma vez entrevistou um autor de desenvolvedor para uma posição contratual. O gerente de contratação foi desdenhoso das publicações em geral, e latiu ao candidato, Então, se você está indo para o trabalho aqui, você prefere escrever livros ou escrever código Sim, doente conceder que em qualquer indústria haverá alguns acadêmicos pura. Mas o que o gerente de contratação perdeu foi as oportunidades para reforçar e afiar conjuntos de habilidades. Enquanto limpava uma velha caixa de livros, me deparei com um tesouro dos anos 80: Programmers at Work. Que contém entrevistas com um muito jovem Bill Gates, Ray Ozzie, e outros nomes bem conhecidos. Cada entrevista e cada insight vale o preço do livro. Na minha opinião, a entrevista mais interessante foi com Butler Lampson. Que deu alguns conselhos poderosos. Para o inferno com a informática. É absolutamente ridículo. Estudar matematica. Aprenda a pensar. Ler. Escreva. Essas coisas são de valor mais duradouro. Aprenda a provar teoremas: Muitas provas se acumulam ao longo dos séculos, o que sugere que essa habilidade é transferível para muitas outras coisas. Butler fala a verdade. Ill acrescentar a esse ponto aprender a jogar diabos advogado contra si mesmo. Quanto mais você pode verificar a realidade de seus próprios processos e de trabalho, melhor será youll ser. O grande scientistauthor de computador Allen Holub fez a conexão entre o desenvolvimento de software e as artes liberais especificamente, o assunto da história. Aqui estava o seu ponto: o que é história Leitura e escrita. O que é desenvolvimento de software Entre outras coisas, ler e escrever. Eu costumava dar a meus alunos T-SQL ensaio perguntas como testes de prática. Um aluno brincou dizendo que eu agia mais como um professor de direito. Bem, assim como o treinador Donny Haskins disse no filme Glory Road, meu caminho é difícil. Acredito firmemente em uma base intelectual forte para qualquer profissão. Assim como as aplicações podem se beneficiar de estruturas, indivíduos e seus processos de pensamento podem se beneficiar de estruturas humanas também. Essa é a base fundamental da erudição. Há uma história que nos anos 70, a IBM expandiu seus esforços de recrutamento nas grandes universidades, focalizando os melhores e mais brilhantes graduados em artes liberais. Mesmo assim, eles reconheceram que os melhores leitores e escritores poderiam algum dia se tornar analistas de programadores de sistemas fortes. (Sinta-se livre para usar essa história para qualquer tipo de RH que insiste que um candidato deve ter um grau de ciência da computação) E falando de história: se por nenhuma outra razão, é importante lembrar o histórico de lançamentos de produtos se eu estou trabalhando em um Site do cliente thats ainda usando o SQL Server 2008 ou mesmo (gasp) SQL Server 2005, tenho que lembrar quais recursos foram implementados nas versões ao longo do tempo. Sempre tem um médico favorito que você gostou porque heshe explicou as coisas em Inglês simples, deu-lhe a verdade reta, e ganhou sua confiança para operar em você Essas são habilidades loucas. E são o resultado da experiência e do TRABALHO DURO que fazem exame de anos e mesmo de décadas para cultivar. Não há garantias de foco no sucesso do trabalho sobre os fatos, tomar alguns riscos calculados quando você tem certeza de que você pode ver o seu caminho para a linha de chegada, deixe as fichas cair onde eles podem, e nunca perder de vista ser exatamente como aquele médico que ganhou sua confiança. Mesmo que alguns dias eu ficar aquém, eu tento tratar o meu cliente e seus dados como um médico iria tratar os pacientes. Mesmo que um médico faz mais dinheiro Existem muitos clichês que eu detesto, mas heres um eu não odeio: Não existe tal coisa como uma pergunta ruim. Como ex-instrutor, uma coisa que atraiu a minha ira foi ouvir alguém criticar outra pessoa por fazer uma pergunta supostamente estúpida. Uma pergunta indica que uma pessoa reconhece que tem alguma lacuna no conhecimento que eles estão procurando preencher. Sim, algumas perguntas são formuladas melhor do que outras, e algumas perguntas exigem a moldação adicional antes que possam ser respondidas. Mas a viagem de formar uma pergunta a uma resposta é provável gerar um processo mental ativo em outro. Há todas as boas coisas. Muitas discussões boas e frutíferas se originam com uma pergunta estúpida. Eu trabalho em toda a linha no SSIS, SSAS, SSRS, MDX, PPS, SharePoint, Power BI, DAX todas as ferramentas na pilha Microsoft BI. Eu ainda escrevo algum código de vez em quando. Mas acho que eu ainda gastar tanto tempo fazendo escrever código T-SQL para dados de perfil como parte do processo de descoberta. Todos os desenvolvedores de aplicativos devem ter bom T-SQL chops. Ted Neward escreve (corretamente) sobre a necessidade de se adaptar às mudanças tecnológicas. Ill acrescentar que a necessidade de se adaptar às mudanças clientemployer. As empresas mudam as regras de negócios. As empresas adquirem outras empresas (ou se tornam o alvo de uma aquisição). Empresas cometem erros na comunicação de requisitos de negócios e especificações. Sim, às vezes podemos desempenhar um papel em ajudar a gerenciar essas mudanças e às vezes foram a mosca, não o pára-brisa. Estes, por vezes, causar grande dor para todos, especialmente o I. T. pessoas. É por isso que o termo fato da vida existe, temos de lidar com ele. Assim como nenhum desenvolvedor escreve bug código livre de cada vez, não I. T. Pessoa lida bem com a mudança cada vez. Uma das maiores lutas que eu tive em meus 28 anos nesta indústria está mostrando paciência e contenção quando as mudanças estão voando de muitas direções diferentes. Aqui é onde a minha sugestão anterior sobre a busca do ar rarificado pode ajudar. Se você consegue assimilar mudanças em seu processo de pensamento, e sem se sentir oprimido, as probabilidades são youll ser um ativo significativo. Nos últimos 15 meses Ive teve que lidar com uma enorme quantidade de mudança profissional. Tem sido muito difícil às vezes, mas eu resolvi que a mudança será a norma e Ive tentou ajustar meus próprios hábitos da melhor maneira possível para lidar com a mudança freqüente (e incerto). É difícil, muito difícil. Mas como o treinador Jimmy Duggan disse no filme A League of Their Own: Claro que é difícil. Se não fosse difícil, todo mundo faria isso. O duro, é o que o torna ótimo. Uma mensagem poderosa. Theres sido falar na indústria ao longo dos últimos anos sobre a conduta em conferências profissionais (e conduta no setor como um todo). Muitos escritores respeitados escreveram editoriais muito bons sobre o tema. Heres minha entrada, para que seu valor. Its a message to those individuals who have chosen to behave badly: Dude, it shouldnt be that hard to behave like an adult. A few years ago, CoDe Magazine Chief Editor Rod Paddock made some great points in an editorial about Codes of Conduct at conferences. Its definitely unfortunate to have to remind people of what they should expect out of themselves. But the problems go deeper. A few years ago I sat on a five-person panel (3 women, 2 men) at a community event on Women in Technology. The other male stated that men succeed in this industry because the Y chromosome gives men an advantage in areas of performance. The individual who made these remarks is a highly respected technology expert, and not some bozo making dongle remarks at a conference or sponsoring a programming contest where first prize is a date with a bikini model. Our world is becoming increasingly polarized (just watch the news for five minutes), sadly with emotion often winning over reason. Even in our industry, recently I heard someone in a position of responsibility bash software tool XYZ based on a ridiculous premise and then give false praise to a competing tool. So many opinions, so many arguments, but heres the key: before taking a stand, do your homework and get the facts . Sometimes both sides are partly rightor wrong. Theres only one way to determine: get the facts. As Robert Heinlein wrote, Facts are your single clue get the facts Of course, once you get the facts, the next step is to express them in a meaningful and even compelling way. Theres nothing wrong with using some emotion in an intellectual debate but it IS wrong to replace an intellectual debate with emotion and false agenda. A while back I faced resistance to SQL Server Analysis Services from someone who claimed the tool couldnt do feature XYZ. The specifics of XYZ dont matter here. I spent about two hours that evening working up a demo to cogently demonstrate the original claim was false. In that example, it worked. I cant swear it will always work, but to me thats the only way. Im old enough to remember life at a teen in the 1970s. Back then, when a person lost hisher job, (often) it was because the person just wasnt cutting the mustard. Fast-forward to today: a sad fact of life is that even talented people are now losing their jobs because of the changing economic conditions. Theres never a full-proof method for immunity, but now more than ever its critical to provide a high level of what I call the Three Vs (value, versatility, and velocity) for your employerclients. I might not always like working weekends or very late at night to do the proverbial work of two people but then I remember there are folks out there who would give anything to be working at 1 AM at night to feed their families and pay their bills. Always be yourselfyour BEST self. Some people need inspiration from time to time. Heres mine: the great sports movie, Glory Road. If youve never watched it, and even if youre not a sports fan I can almost guarantee youll be moved like never before. And Ill close with this. If you need some major motivation, Ill refer to a story from 2006. Jason McElwain, a high school student with autism, came off the bench to score twenty points in a high school basketball game in Rochester New York. Heres a great YouTube video. His mother said it all . This is the first moment Jason has ever succeeded and is proud of himself. I look at autism as the Berlin Wall. He cracked it. To anyone who wanted to attend my session at todays SQL Saturday event in DC I apologize that the session had to be cancelled. I hate to make excuses, but a combination of getting back late from Detroit (client trip), a car thats dead (blown head gasket), and some sudden health issues with my wife have made it impossible for me to attend. Back in August, I did the same session (ColumnStore Index) for PASS as a webinar. You can go to this link to access the video (itll be streamed, as all PASS videos are streamed) The link does require that you fill out your name and email address, but thats it. And then you can watch the video. Feel free to contact me if you have questions, at kgoffkevinsgoff November 15, 2013 Getting started with Windows Azure and creating SQL Databases in the cloud can be a bit daunting, especially if youve never tried out any of Microsofts cloud offerings. Fortunately, Ive created a webcast to help people get started. This is an absolute beginners guide to creating SQL Databases under Windows Azure. It assumes zero prior knowledge of Azure. You can go to the BDBI Webcasts of this website and check out my webcast (dated 11102013). Or you can just download the webcast videos right here: here is part 1 and here is part 2. You can also download the slide deck here. November 03, 2013 Topic this week: SQL Server Snapshot Isolation Levels, added in SQL Server 2005. To this day, there are still many SQL developers, many good SQL developers who either arent aware of this feature, or havent had time to look at it. Hopefully this information will help. Companion webcast will be uploaded in the next day look for it in the BDBI Webcasts section of this blog. October 26, 2013 Im going to start a weekly post of T-SQL tips, covering many different versions of SQL Server over the years Heres a challenge many developers face. Ill whittle it down to a very simple example, but one where the pattern applies to many situations. Suppose you have a stored procedure that receives a single vendor ID and updates the freight for all orders with that vendor id. create procedure dbo. UpdateVendorOrders update Purchasing. PurchaseOrderHeader set Freight Freight 1 where VendorID VendorID Now, suppose we need to run this for a set of vendor IDs. Today we might run it for three vendors, tomorrow for five vendors, the next day for 100 vendors. We want to pass in the vendor IDs. If youve worked with SQL Server, you can probably guess where Im going with this. The big question is how do we pass a variable number of Vendor IDs Or, stated more generally, how do we pass an array, or a table of keys, to a procedure Something along the lines of exec dbo. UpdateVendorOrders SomeListOfVendors Over the years, developers have come up with different methods: Going all the way back to SQL Server 2000, developers might create a comma-separated list of vendor keys, and pass the CSV list as a varchar to the procedure. The procedure would shred the CSV varchar variable into a table variable and then join the PurchaseOrderHeader table to that table variable (to update the Freight for just those vendors in the table). I wrote about this in CoDe Magazine back in early 2005 (code-magazinearticleprint. aspxquickid0503071ampprintmodetrue. Tip 3) In SQL Server 2005, you could actually create an XML string of the vendor IDs, pass the XML string to the procedure, and then use XQUERY to shred the XML as a table variable. I also wrote about this in CoDe Magazine back in 2007 (code-magazinearticleprint. aspxquickid0703041ampprintmodetrue. Tip 12)Also, some developers will populate a temp table ahead of time, and then reference the temp table inside the procedure. All of these certainly work, and developers have had to use these techniques before because for years there was NO WAY to directly pass a table to a SQL Server stored procedure. Until SQL Server 2008 when Microsoft implemented the table type. This FINALLY allowed developers to pass an actual table of rows to a stored procedure. Now, it does require a few steps. We cant just pass any old table to a procedure. It has to be a pre-defined type (a template). So lets suppose we always want to pass a set of integer keys to different procedures. One day it might be a list of vendor keys. Next day it might be a list of customer keys. So we can create a generic table type of keys, one that can be instantiated for customer keys, vendor keys, etc. CREATE TYPE IntKeysTT AS TABLE ( IntKey int NOT NULL ) So Ive created a Table Typecalled IntKeysTT . Its defined to have one column an IntKey. Nowsuppose I want to load it with Vendors who have a Credit Rating of 1..and then take that list of Vendor keys and pass it to a procedure: DECLARE VendorList IntKeysTT INSERT INTO VendorList SELECT BusinessEntityID from Purchasing. Vendor WHERE CreditRating 1 So, I now have a table type variable not just any table variable, but a table type variable (that I populated the same way I would populate a normal table variable). Its in server memory (unless it needs to spill to tempDB) and is therefore private to the connectionprocess. OK, can I pass it to the stored procedure now Well, not yet we need to modify the procedure to receive a table type. Heres the code: create procedure dbo. UpdateVendorOrdersFromTT IntKeysTT IntKeysTT READONLY update Purchasing. PurchaseOrderHeader set Freight Freight 1 FROM Purchasing. PurchaseOrderHeader JOIN IntKeysTT TempVendorList ON PurchaseOrderHeader. VendorID Te mpVendorList. IntKey Notice how the procedure receives the IntKeysTT table type as a Table Type (again, not just a regular table, but a table type). It also receives it as a READONLY parameter. You CANNOT modify the contents of this table type inside the procedure. Usually you wont want to you simply want to read from it. Well, now you can reference the table type as a parameter and then utilize it in the JOIN statement, as you would any other table variable. Então, você tem. A bit of work to set up the table type, but in my view, definitely worth it. Additionally, if you pass values from , youre in luck. You can pass an ADO data table (with the same tablename property as the name of the Table Type) to the procedure. For developers who have had to pass CSV lists, XML strings, etc. to a procedure in the past, this is a huge benefit. Finally I want to talk about another approach people have used over the years. SQL Server Cursors. At the risk of sounding dogmatic, I strongly advise against Cursors, unless there is just no other way. Cursors are expensive operations in the server, For instance, someone might use a cursor approach and implement the solution this way: DECLARE VendorID int DECLARE dbcursor CURSOR FASTFORWARD FOR SELECT BusinessEntityID from Purchasing. Vendor where CreditRating 1 FETCH NEXT FROM dbcursor INTO VendorID WHILE FETCHSTATUS 0 EXEC dbo. UpdateVendorOrders VendorID FETCH NEXT FROM dbcursor INTO VendorID The best thing Ill say about this is that it works. And yes, getting something to work is a milestone. But getting something to work and getting something to work acceptably are two different things. Even if this process only takes 5-10 seconds to run, in those 5-10 seconds the cursor utilizes SQL Server resources quite heavily. Thats not a good idea in a large production environment. Additionally, the more the of rows in the cursor to fetch and the more the number of executions of the procedure, the slower it will be. When I ran both processes (the cursor approach and then the table type approach) against a small sampling of vendors (5 vendors), the processing times where 260 ms and 60 ms, respectively. So the table type approach was roughly 4 times faster. But then when I ran the 2 scenarios against a much larger of vendors (84 vendors), the different was staggering 6701 ms versus 207 ms, respectively. So the table type approach was roughly 32 times faster. Again, the CURSOR approach is definitely the least attractive approach. Even in SQL Server 2005, it would have been better to create a CSV list or an XML string (providing the number of keys could be stored in a scalar variable). But now that there is a Table Type feature in SQL Server 2008, you can achieve the objective with a feature thats more closely modeled to the way developers are thinking specifically, how do we pass a table to a procedure Now we have an answer Hope you find this feature help. Feel free to post a comment. SQL Server 2012 Analysis Services (SSAS) DMVs By: Scott Murray Read Comments (6) Related Tips: Analysis Services Administration What are the SQL Server Analysis Services (SSAS) 2012 DMVs and how can they be used In my previous tip on XMLA both the Execute and Discover methods were discussed in context of running XMLA queries. The discover method exposes metadata about a SSAS database however the data is returned in XML form. As an alternative to the discover method, SSAS provides a group of dynamic management views (DMVs for short) which can be queried to return the same data as the discover method. However, by using these DMVs, the data is returned in a tabular format which is generally easier to read and use as a basis for reports. The queries are DMX, but they have the look and feel of SQL with some caveats. The DMVs can be broken up into two main categories: the DBSCHEMAMDSCHEMA DMVs which retrieve metadata about the SSAS database, such as cube structure and dimension structure and the Discover DMVs which retrieve monitoring data such a current connections and locks. SSAS MDSCHEMA and DBSCHEMA DMVs The SSAS DMVs act in many ways like regular SQL DMVs and return data in a table format, at least in most cases. The information that can be queried covers everything from the connections that are currently active to the amount of memory being used to what dimensions are part of the cube. Furthermore, you can even query a dimension to get its members. Even though the queries are SQL-like, you can not use the following: Last, and probably equally important, in order to run queries against the SSAS database, system administrator permissions are required. The best way to show what the views can do is to review several number of examples which will in turn convey the limitations that come into play with several of the DMVs. Probably the best place to start is with a query to get a list of the DMVs available to query. The below MDX queries will display the list of views which can be queried. Note that the word views is used very loosely as these DMVs are SQL-like but not pure SQL. In order to run these queries, open SSMS and connect to your SSAS database as displayed below. For our examples we will be using the AdventureWorks 2012 DataWarehouse sample database available on CodePlex, msftdbprodsamples. codeplexreleasesview55330. Be sure to select the AdventureWorksDW2012 database and verify the query type is set to MDX. If MDX is not selected, you can set the query type by clicking on the MDX button in the tool bar. The query results are partially displayed in the below screen print. This table list is roughly equivalent to the DMVs that are available to query against the SSAS database. For details on each of these row sets, MSDN has a DMV reference sheet available at: msdn. microsoften-uslibraryhh230820.aspxbkmkref. Next, we can run the following query to get a list of cubes in a particular database. Of course there are a few caveats with the query results shown below. First you will notice that only two cubes are displayed in the objective explorer (left side of above screen print), while the query results show seven rows. The reason for this discrepancy is that the results include Perspectives in addition to the regular cubes. Thus, a simple way to return just the cubes and not the perspectives is to adjust our query as shown in the next illustration. In this case, the criteria in the where clause is a bit of cheat in that it looks for a blank value for the BaseCubeName by using the less than operator. Next we can get a list of dimensions using the MDSCHEMADIMENSIONS DMV. Of course a few caveats exists with the query results shown below. The dimensions are listed multiple times for instance, the Account dimension is listed seven times. One dimension exists for each cube measure group additionally, one dimension, the one whose cube name begins with the is the cube level dimension. Furthermore, the dimension caption displays the name that the end users see. Drilling into the dimension, we can next use the MDSCHEMAMEASUREGROUPDIMENSIONS DMV, as displayed below. This DMV breaks out the dimensions at the measure group granularity level. Notice that I have included two items in the Order By clause. Unfortunately, including more than one item in the order clause is not supported and produces the following error. Using just one order by field and adding the cube name to the where clause produces better results which are illustrated below. Again, notice we have duplicates as we did before with the MDSCHEMADIMENSIONS DMV. Before moving on to some of the monitoring DMVs, lets review the measure MDSCHEMAMEASURES DMV. As illustrated below, in addition to the normal name and visibility information available from the dimension DMVs, the MDSCHEMAMEASURES DMV conveys the format used for the measure and the aggregation method, which tells how to aggregate the measure such as Sum, Average, or Custom (see msdn. microsoften-uslibraryms126250.aspx ). The DMV also displays the formula used in a calculated measure in the Expression field which is helpful when checking multiple calculated values at one time non calculated measure have no data in the expression field. SSAS Discover DMVs The SSAS Discover DMVs retrieve data used to monitor a SSAS database. Some data points that can be retrieved include the query execution times, current locks, CPU and memory usage, and current connections. We will start with the DISCOVERCONNECTIONS DMV. This DMV provides us with a wealth of details about the current sessions including the Last Command to be run, how long the command took to run, how much memory the session used, and how many reads and writes were used. This DISCOVERCOMMANDS DMV provides us with similar information at the command level. You will also notice that you can do a Select to retrieve all columns from the DMV however, just as with other select statements, I would recommend only retrieving the columns needed. Some of the Discover DMVs require the use of SYSTEMRESTRICTSCHEMA and also require passing in additional parameters. In essence, this means that instead of writing a select directly against the DMV, we query the SYSTEMRESTRICTSCHEMA and then specify the DMV and any other parameters required when writing the query. For example, the below query integrates the DISCOVERINSTANCES DMV. In this case, only one parameter is required, INSTANCENAME. Notice how the from uses the SYSTEMRESTRICTSCHMEA. The DISCOVERINSTANCES DMV returns the following data about the instance. Using the SYSTEM. DBSCHEMATABLES DMV, you can explore many of the other Discover SSAS DMVs. Conclusion Using the SSAS DMVs can return a plethora of information about a SSAS cubes metadata and a cubes current state, from a monitoring standpoint. These DMVs are easier to use than XMLA related queries as the data is returned in tabular format and the queries are written, in most cases, in a SQL-like manner. The results, depending on the DMV, can provide much of the information needed for a SSAS administrator to profile and monitor the SSAS cubes. Next Steps Last Update: 7262013Using DAX to retrieve tabular data Robert Sheldon In my last article, 8220Getting Started with the SSAS Tabular Model ,8221 I introduced you to the SQL Server Analysis Services (SSAS) tabular database and how to access its components in SQL Server Management Studio (SSMS). This article continues that discussion by demonstrating how to use the Data Analysis Expressions (DAX) language to retrieve data from your tabular database. DAX has a rather unique history in that it8217s a formula language with its roots in PowerPivot, an in-memory data exploration tool that brought the tabular model to Excel. In fact, DAX is often considered an extension to the formula language used in Excel. When Microsoft added support for the tabular model in SSAS 2012, they included support for both DAX and Multidimensional Expressions (MDX), the language traditionally used to access SSAS multidimensional data. You can use either DAX or MDX to query data in an SSAS tabular database. However, you cannot use MDX if the database is configured to run in DirectQuery mode. In addition, some client applications, such as Power View, can issue DAX queries only. As a result, if you plan to support tabular databases, you should have at least a basic understanding of how to use DAX to access data in those databases. Because DAX has its roots in PowerPivot, much of what has been written about the language has focused on how to create expressions that define measures and calculated columns. But there might be times when you want to use DAX to access data directly from a tabular database, either by issuing queries in SSMS or by creating them in other client applications. This article explains how to get started writing DAX queries within SSMS and provides numerous examples that demonstrate each concept. For these examples, we use the AdventureWorks Tabular Model SQL 2012 database, available as a SQL Server Data Tools tabular project from the AdventureWorks CodePlex site. Retrieving Table Data To query data in an SSAS tabular database from within SSMS, you must first connect to the SSAS instance that contains the database and then open an MDX query window. You have to use an MDX query window because SSMS currently does not support a DAX-specific query window. However, you can write DAX queries directly in the MDX window without taking any other steps. When using DAX to retrieve tabular data, your entire statement is founded on the evaluate clause. The clause begins with the evaluate keyword, followed by a table expression, enclosed in parenthesis. The table expression defines the results of your query. The simplest table expression is one that specifies the name of the table, enclosed in single quotes. When you specify only the table name, all rows and columns are returned. For example, the following evaluate clause retrieves all data from the InternetSales table: Notice that you first specify the order by keywords, followed by the column name on which you want to order the data. If can include more than one column, but you must separate them with a comma. When specifying the column name, you must precede it with the table name, enclosed in single quotes, and then the column name, enclosed in brackets. This method of referencing a column is typical of the approach you generally use when referencing columns in your DAX statements. With the addition of the order by clause, the results are now sorted by the ProductKey column, as shown in Figure 2. Figure 2: Ordering a result set based on the ProductKey values As handy as it is to be able to pull all the data from a table, more often than not you won8217t want to. For instance, at times you8217ll likely want to retrieve only specific columns. Unfortunately, DAX makes retrieving only some table columns a less than straightforward process, so you must use a workaround to get the information you need. One of the easiest solutions is to use the summarize function. This function groups data based on specified columns in order to aggregate data in other columns, similar to how a GROUP BY clause works in a T-SQL SELECT statement. However, you can also use the summarize function to return all rows in a table without grouping any of the data. To do so, you must first include a column or columns that uniquely identify each row in the table. For example, the following evaluate clause uses the summarize function to retrieve the Sales Order Number and Sales Order Line Number columns: When you use the summarize function, you specify the function name and then the arguments passed into the function. The first argument is your base table. All subsequent arguments are the columns you want to include in the result set. As you can see in the above example, the arguments are enclosed in parentheses and separated with commas. The summarize function groups the data by the values in the specified columns. However, together the Sales Order Number and Sales Order Line Number columns uniquely identify each row in the table, so all rows are returned and no values are grouped or summarized. Notice, too, that the order by clause now includes the two columns specified in the summarize function, separated by a comma. Figure 3 shows some of the rows returned by the DAX statement: Figure 3: Retrieving distinct values from a table If you were to scroll down these results, you would find a number of repeating Sales Order Number values, but each set of the repeated values would include unique Sales Order Line Number values, which is what makes each row unique. In other words, no two rows would share the same Sales Order Number value and the same Sales Order Line Number value. Of course, you8217re likely to want to include additional columns as well, once you8217ve identified the columns that uniquely identify each row, in which case, you need only add those columns to the mix. In the following example, the ProductKey and OrderDate columns have been added to the summarize function: As you can see in Figure 4, the results now include the additional columns, sorted by the Sales Order Number and Sales Order Line Number columns. Figure 4: Retrieving specific columns from a table The examples so far have demonstrated how to return all rows in a table. However, the nature of SSAS and the tabular model suggest that, in many cases, you8217ll want to work with summarized data. After all, conducting meaningful analysis often depends on the ability to aggregate large datasets. And the summarize function can help perform much of that aggregation. So let8217s take a closer look at that function. Summarizing Data As mentioned earlier, the columns you specify in the summarize function form the basis of how the data is grouped. In the previous two examples, we chose columns that uniquely identified each row, so no real grouping was performed, at least not in the sense that one would expect from a function used to group and summarize data. However, suppose we were to now remove the Sales Order Number and Sales Order Line Number columns, as shown in the following example: As you can see, this time round we8217re grouping our data on the ProductKey and Order Date columns only, and we8217re also doing something else, adding a third column that aggregates the data. The new column is considered a calculated column (or extension column). When adding a calculated column in this way, we include two parts. The first is the name of the new column ( Total Sales Amount ), enclosed in double quotes. The second part is an expression that defines the column8217s values. In this case, we8217re using the sum aggregate function to add together the Sales Amount values. To do so, we need only specify the function name, followed by the column, enclosed in parentheses. Now our results include three columns, with the values grouped together by the ProductKey and Order Date columns and the amount of sales for each grouping added to the Total Sales Amount column, as shown in Figure 5. Figure 5: Summarizing data in a table As you can see, DAX lets us easily get the data we need from our table. However, you might find that you want to include columns from other tables in your result set, as you would when joining tables in a T-SQL SELECT statement. Fortunately, DAX and the tabular model makes it simple to retrieve these columns. For example, suppose we want to retrieve the product names instead of the product numbers and the order year instead of a specific date and time. We can easily achieve this by modifying our summarize function as follows: As you can see, in place of the ProductKey column, we now have the Product Name column from the Product table, and instead of the Order Date column we have the Calendar Year column from the Date table. NOTE: Pulling data from the Calendar Year column in this way masks the fact that multiple relationships exist between the Internet Sales table and the Date table. The first of these relationships is defined on the OrderDateKey column in the Internet Sales table. As a result, the Calendar Year value returned by our statement is based on the date represented by that key. An explanation of the logic behind all this is beyond the scope of this article, but know that what we8217ve done in our example serves its main purpose: to demonstrate how easily we can retrieve data from other tables. In addition to switching out columns, we8217ve also updated our order by clause to reflect the new columns. Now are results our substantially different, as shown in Figure 6. Figure 6: Retrieving data from other tables As you can see, we8217ve grouped our data first by product name and then by the calendar year, with sales totals provided for each group. If you were to scroll down the list, you would find that our results include other years as well. Not surprisingly, these results are much quicker to comprehend because they include easily identifiable information: the product names and sales years. In addition, we can easily add more columns. The following example is similar to the last but now includes the Product Subcategory Name column from the Product Subcategory table and the Product Category Name column from the Product Category table: To use the ROLLUP function, you need only to precede the column name with the function name and enclose the column name in parentheses. As you can see in Figure 8, our results now include an additional row for each product. The new row provides totals for that product for all years. Figure 8: Using the ROLLUP operator to summarize data Not surprisingly, there8217s far more you can do when using DAX to summarize data, but what we8217ve covered here should help you get started. And you8217ve seen how specific we can be in terms of which columns we return. So now let8217s look at how we can filter data even further. Filtering Data One of the easiest ways to filter data in a DAX statement is to use the filter function. The function takes two arguments: a table expression and a filter. The table expression can be the name of a table or an expression that returns a table. The filter is a Boolean expression that is evaluated for each row returned by the table expression. Any row for which the expression evaluates to true is included in the result set. Let8217s look at an example to better understand how the filter function works. In the following evaluate clause, the filter function filters data in the Internet Sales table: In our example, we once again we start with a filter function, but this time, as our first argument, we use the addcolumns function to return a table. The addcolumns function takes as its first argument a table or table expression. In this case, we8217re using the Product table. After we specify our table, we add a definition for a calculated column, just like we did with the summarize function. In this case, however, the column is named Net Profit . and the column8217s values are based on an expression that subtracts the Standard Cost value from the List Price column. We then filter our results so that only rows with a List Price value greater than 0 are included in the result set. Figure 9 shows part of the results returned by the DAX statement. Notice the Net Profit column added after all the table8217s other columns. Figure 9: Adding columns to a table Of course, you8217ll often want to be more specific with your table expression, rather than simply returning the entire table. For example, you can use the summarize function as your table expression. In fact, the addcolumns function can be particularly helpful when used in conjunction with the summarize function. Let8217s take a step back. As you8217ll recall from earlier examples, we used the summarize function to add the Total Sales Amount and Total Cost computed columns to our result set. However, in some cases, you8217ll see better performance if you use the addcolumns function to create those columns, rather than creating the computed columns within the summarize function, as shown in the following example: In this case, the summarize function specifies only the columns on which to group the data. The function returns a table as the first argument to the addcolumns function. We can then add our computed columns as arguments to the addcolumns function. The only thing to remember, however, if we add columns in this way and those columns aggregate data, we must also use the calculate function to call our aggregated column. (This has to do with the context in which DAX evaluates data.) Figure 10 shows part of the results returned by the DAX statement. Figure 10: Adding columns when summarizing data Using the addcolumns function to add computed columns works in most, but not all, situations. For example, you cannot use this approach when you want to use the ROLLUP function. (Be sure to check the DAX documentation for specifics on when to use addcolumns .) However, when you can use the addcolumns function in conjunction with the summarize function, you should see better performance. Moving Ahead with DAX Now that you8217ve gotten a taste of how to use DAX to retrieve tabular data, you should be ready to start putting DAX to work. Keep in mind, however, that what we8217ve covered here only scratches the surface of what you can do with DAX. It is a surprisingly rich language that includes a number of methods for retrieving and summarizing data. In future articles in this series, we8217ll look at how to access a tabular data from other client applications, often using DAX in the process. What you8217ve learned in this article should provide you with the foundation you need to facilitate that data access. Keep in mind, however, that the better you understand DAX, the better you8217ll be able to make use of your tabular data. Subscribe for more articles Fortnightly newsletters help sharpen your skills and keep you ahead, with articles, ebooks and opinion to keep you informed. Want more Subscribe to our fortnightly newsletter Related articles Also in Database With the rise of NoSQL databases that are exploiting aspects of SQL for querying, and are embracing full transactionality, is there a danger of the data-document models hierarchical nature causing a fundamental conflict with relational theory We asked our relational expert, Hugh Bin-Haad to expound a difficult area for database theorists. hellip Read more Also in DAX Following on from his first four articles on using Data Analysis Expressions (DAX) with tabular databases, Robert Sheldon dives into some of the DAX statistical functions available, demonstrating which are the most useful and examples of how they work. hellip Read more Also in PowerPivot Although it is well-known how to create a tabular database in PowerPivot, it is less obvious that there are several useful options for retrieving SSAS tabular data into Excel. This provides an easy way of manipulating, visualizing and analyzing the data without needing to know the details of SSAS and the tabular model. hellip Read more Also in Reporting Services The Power Query Formula Language (PQFL) is a functional language that drives the Power BI transformations, and allows you to create mashup queries from scratch. Rob demonstrates how to use it in Power BI Desktop to extract data from its source, filter rows, specify the columns, clean the data, and create visualisations. hellip Read more copy 2005 - 2017 Red Gate Software Ltd What do you think of the new Simple Talk Give us your feedback

No comments:

Post a Comment