21 SQL para análise e relatórios Para executar essas operações, as funções analíticas adicionam vários novos elementos ao processamento SQL. Esses elementos se baseiam no SQL existente para permitir expressões de cálculo flexíveis e poderosas. Com poucas exceções, as funções analíticas possuem esses novos elementos. O fluxo de processamento está representado na Figura 21-1. Figura 21-1 Ordem de processamento Os conceitos essenciais utilizados nas funções analíticas são: o processamento de consultas usando funções analíticas ocorre em três etapas. Primeiro, todas as junções, ONDE. As cláusulas GROUP BY e HAVING são realizadas. Em segundo lugar, o conjunto de resultados é disponibilizado para as funções analíticas e todos os seus cálculos ocorrem. Em terceiro lugar, se a consulta tiver uma cláusula ORDER BY no final, a ORDER BY é processada para permitir uma ordem de saída precisa. A ordem de processamento é mostrada na Figura 21-1. Partições de conjunto de resultados As funções analíticas permitem aos usuários dividir conjuntos de resultados de consulta em grupos de linhas chamados de partições. Observe que o termo partições usadas com funções analíticas não está relacionado com o recurso de partição de tabela. Ao longo deste capítulo, o termo "partições" refere-se apenas ao significado relacionado às funções analíticas. As partições são criadas após os grupos definidos com as cláusulas GROUP BY, por isso estão disponíveis para todos os resultados agregados, como somas e médias. As divisões de partição podem ser baseadas em colunas ou expressões desejadas. Um conjunto de resultados de consulta pode ser particionado em apenas uma partição que contém todas as linhas, algumas partições grandes ou muitas partições pequenas que possuem apenas algumas linhas cada. Para cada linha de uma partição, você pode definir uma janela deslizante de dados. Esta janela determina o intervalo de linhas usadas para executar os cálculos para a linha atual. Os tamanhos das janelas podem ser baseados em um número físico de linhas ou um intervalo lógico, como o tempo. A janela tem uma linha inicial e uma linha final. Dependendo da sua definição, a janela pode se mover em uma ou em ambas as extremidades. Por exemplo, uma janela definida para uma função de soma cumulativa teria sua linha inicial fixada na primeira linha de sua partição, e sua linha final deslizaria desde o ponto de partida até a última linha da partição. Em contraste, uma janela definida para uma média móvel teria seus pontos de partida e final deslizando para que eles mantenham uma faixa física ou lógica constante. Uma janela pode ser definida como grande como todas as linhas em uma partição ou apenas uma janela deslizante de uma linha dentro de uma partição. Quando uma janela está perto de uma borda, a função retorna os resultados apenas para as linhas disponíveis, em vez de avisá-lo de que os resultados não são o que deseja. Ao usar as funções da janela, a linha atual é incluída durante os cálculos, portanto, você deve especificar (n -1) quando estiver lidando com n itens. Cada cálculo executado com uma função analítica é baseado em uma linha atual dentro de uma partição. A linha atual serve como o ponto de referência que determina o início e o fim da janela. Por exemplo, um cálculo de média móvel centrada poderia ser definido com uma janela que contenha a linha atual, as seis linhas precedentes e as seis linhas seguintes. Isso criaria uma janela deslizante de 13 linhas, como mostrado na Figura 21-2. Figura 21-2 Janela deslizante Exemplo Funções de classificação Uma função de classificação calcula a classificação de um registro em comparação com outros registros no conjunto de dados com base nos valores de um conjunto de medidas. Os tipos de função de classificação são: Cálculo de Regressão Linear de Amostra Neste exemplo, calculamos uma linha de regressão de mínimos quadrados comuns que expressa a quantidade vendida de um produto como uma função linear do preço da lista de produtos. Os cálculos são agrupados pelo canal de vendas. Os valores INCLINAÇÃO. INTCPT. RSQR são declive, interceptação e coeficiente de determinação da linha de regressão, respectivamente. O valor (número inteiro) COUNT é o número de produtos em cada canal para quem a quantidade vendida e os dados do preço da lista estão disponíveis. Álgebra linear A álgebra linear é um ramo da matemática com uma ampla gama de aplicações práticas. Muitas áreas têm tarefas que podem ser expressas usando álgebra linear, e aqui estão alguns exemplos de vários campos: estatísticas (regressão linear múltipla e análise de componentes principais), mineração de dados (clustering e classificação), bioinformática (análise de dados de microarrays), pesquisa operacional (Cadeia de suprimentos e outros problemas de otimização), econometria (análise de dados da demanda do consumidor) e finanças (problemas de alocação de ativos). Várias bibliotecas para álgebra linear estão disponíveis gratuitamente para qualquer um usar. O pacote Oracles UTLNLA expõe os tipos de dados matriz PLSQL e os subprogramas wrapper PLSQL para duas das mais populares e robustas dessas bibliotecas, BLAS e LAPACK. A álgebra linear depende da manipulação da matriz. A realização de manipulação de matriz em PLSQL no passado exigiu inventar uma representação de matriz baseada em tipos de dados nativos do PLSQL e depois escrever rotinas de manipulação de matriz a partir do zero. Isso exigiu esforço de programação substancial e o desempenho da implementação resultante foi limitado. Se os desenvolvedores escolherem enviar dados para pacotes externos para processamento em vez de criar suas próprias rotinas, a transferência de dados para trás e para frente pode levar muito tempo. O uso do pacote UTLNLA permite que os dados permaneçam dentro da Oracle, remova o esforço de programação e oferece uma implementação rápida. Exemplo 21-19 Álgebra Linear Aqui está um exemplo de como o suporte de álgebra linear Oracles poderia ser usado para análise de negócios. Invoca um aplicativo de regressão linear múltipla construído usando o pacote UTLNLA. O aplicativo de regressão múltipla é implementado em um objeto chamado OLSRegression. Observe que os arquivos de exemplo para o OLS Regression podem ser encontrados em ORACLEHOMEplsqldemo. Considere o cenário de um varejista analisando a eficácia do seu programa de marketing. Cada uma das suas lojas aloca seu orçamento de marketing nos seguintes programas possíveis: anúncios de mídia (mídia), promoções (promo), cupons de desconto (disct) e endereços diretos (dmail). A análise de regressão cria uma relação linear entre a quantidade de vendas que uma loja média possui em um determinado ano (vendas) e as despesas com os quatro componentes do programa de marketing. Suponha que os dados de marketing estejam armazenados na tabela a seguir: então, você pode construir o seguinte modelo linear de comercialização usando coeficientes: Este modelo pode ser implementado como a seguinte visão, que se refere ao objeto de regressão OLS: Usando essa visão, um marketing O gerenciador de programas pode realizar uma análise, como é este modelo de marketing de vendas razoável para os dados do ano de 2004. Essa é a correlação múltipla maior do que algum valor aceitável, digamos, 0.9 O SQL para essa consulta pode ser o seguinte: você também pode Resolva questões como o que é a receita de vendas da linha de base esperada de uma loja sem programas de marketing em 2003 ou qual componente do programa de marketing foi o mais efetivo em 2004, ou seja, um aumento de dólar no qual o programa produziu o maior aumento esperado em Vendas Consulte Referência de Pacotes e Tipos do PLSQL do Oracle Database para obter mais informações sobre o uso do pacote UTLNLA e álgebra linear. Itens frequentes Em vez de contar com a frequência com que ocorre um determinado evento (por exemplo, com que frequência alguém comprou leite na mercearia), você pode achar útil a conta com que frequência vários eventos ocorrem juntos (por exemplo, com que frequência alguém comprou o leite E cereais juntos na mercearia). Você pode contar estes vários eventos usando o que é chamado de conjunto de itens freqüentes, que é, como o nome indica, um conjunto de itens. Alguns exemplos de itens podem ser todos os produtos que um determinado cliente comprou em uma única viagem ao supermercado (comumente chamado de cesta de mercado), as páginas da web que um usuário acessou em uma única sessão ou os serviços financeiros que um dado O cliente utiliza. A motivação prática para usar um conjunto de itens freqüentes é encontrar esses conjuntos de itens que ocorrem com mais freqüência. Se você analisar os dados do ponto de venda de uma mercearia, você pode, por exemplo, descobrir que o leite e as bananas são os itens mais comprados. Os itens de itens freqüentes foram assim utilizados em ambientes de inteligência de negócios por muitos anos, sendo o mais comum para análise de cesta de mercado no setor varejista. Os cálculos freqüentes de conjunto de itens são integrados com o banco de dados, operando em cima de tabelas relacionais e acessados através de SQL. Esta integração fornece os seguintes benefícios principais: as aplicações que anteriormente dependiam de operações freqüentes de conjuntos de itens agora se beneficiam de um desempenho significativamente melhorado, bem como de uma implementação mais simples. Os aplicativos baseados em SQL que não usavam anteriormente conjuntos de itens freqüentes agora podem ser facilmente estendidos para aproveitar esta funcionalidade. A análise freqüente dos itens é realizada com o pacote PLSQL DBMSFREQUENTITEMSETS. Consulte Referência de Pacotes e Tipos do Oracle Database PLSQL para obter mais informações. Além disso, existe um exemplo de uso freqüente de itens em itens de itens freqüentes. Outras funções estatísticas Oracle apresenta um conjunto de funções estatísticas SQL e um pacote de estatísticas, DBMSSTATFUNCS. Esta seção lista algumas das novas funções, juntamente com a sintaxe básica. Estatísticas descritivas Você pode calcular as seguintes estatísticas descritivas: Mediana de um conjunto de dados Você pode calcular as seguintes estatísticas paramétricas: Spearans rho Coeficiente Kendalls tau-b Coeficiente Além das funções, esta versão possui um novo pacote PLSQL, DBMSSTATFUNCS. Ele contém a função estatística descritiva RESUMO juntamente com funções para suportar a distribuição adequada. A função RESUMO resume uma coluna numérica de uma tabela com uma variedade de estatísticas descritivas. As cinco funções de montagem de distribuição suportam distribuições normais, uniformes, Weibull, Poisson e exponenciais. Função WIDTHBUCKET Para uma determinada expressão, a função WIDTHBUCKET retorna o número do balde que o resultado dessa expressão será atribuído após a avaliação. Você pode gerar histogramas de equiwidth com esta função. Equiwidth histogramas dividem conjuntos de dados em baldes cujo tamanho de intervalo (valor mais alto para menor valor) é igual. O número de linhas detidas por cada balde variará. Uma função relacionada, NTILE. Cria baldes de equiheight. Equiwidth histogramas só podem ser gerados para tipos numéricos, data ou data-hora. Portanto, os três primeiros parâmetros devem ser todas as expressões numéricas ou todas as expressões de data. Não são permitidos outros tipos de expressões. Se o primeiro parâmetro for NULL. O resultado é NULL. Se o segundo ou o terceiro parâmetro for NULL. Uma mensagem de erro é retornada, pois um valor NULL não pode indicar qualquer ponto final (ou qualquer ponto) para um intervalo em uma data ou uma dimensão de valor numérico. O último parâmetro (número de baldes) deve ser uma expressão numérica que avalie para um valor inteiro positivo 0, NULL. Ou um valor negativo resultará em um erro. Os baldes estão numerados de 0 a (n 1). O balde 0 contém a contagem de valores inferiores ao mínimo. O balde (n 1) contém a contagem de valores maiores ou iguais ao valor máximo especificado. WIDTHBUCKET Sintaxe O WIDTHBUCKET leva quatro expressões como parâmetros. O primeiro parâmetro é a expressão que o histograma equiwidth é para. Os segundo e terceiro parâmetros são expressões que indicam os pontos finais do intervalo aceitável para o primeiro parâmetro. O quarto parâmetro indica o número de baldes. Considere os seguintes dados dos clientes da tabela. Que mostra os limites de crédito de 17 clientes. Estes dados são reunidos na consulta mostrada no Exemplo 21-20. Na tabela de clientes. A coluna custcreditlimit contém valores entre 1500 e 15000, e podemos atribuir os valores a quatro baldes de equiwidth, numerados de 1 a 4, usando WIDTHBUCKET (custcreditlimit, 0, 20000, 4). Idealmente, cada balde é um intervalo de abertura fechada da linha do número real, por exemplo, o número de balde 2 é atribuído a pontuações entre 5000.0000 e 9999.9999. Às vezes denotado 5000, 10000) para indicar que 5.000 está incluído no intervalo e 10.000 são excluídos. Para acomodar valores fora do intervalo de 0, 20.000), os valores inferiores a 0 são atribuídos a um balde de fluxo inferior designado que é numerado 0 e valores atribuídos a um balde de transbordo designado que é numerado 5 (baldes numéricos 1 em geral). Consulte a Figura 21-3 para obter uma ilustração gráfica de como os baldes são atribuídos. Figura 21-3 Atribuições de balde Você pode especificar os limites na ordem inversa, por exemplo, WIDTHBUCKET (custcreditlimit. 20000. 0. 4). Quando os limites são invertidos, os baldes serão intervalos abertos e fechados. Neste exemplo, o número de balde 1 é (15000,20000, o número de balde 2 é (10000,15000 e o número de balde 4, é (0, 5000. O balde de estouro será numerado 0 (20000. infinito) e a balde subfluxa Será numerado 5 (- infinito. 0. É um erro se o parâmetro de contagem de balde for 0 ou negativo. Exemplo 21-20 WIDTHBUCKET A consulta seguinte mostra os números de balde para os limites de crédito na tabela de clientes para ambos os casos em que o Os limites são especificados em ordem regular ou inversa. Usamos um intervalo de 0 a 20,000. Funções agregadas definidas pelo usuário O Oracle oferece uma facilidade para criar suas próprias funções, chamadas funções agregadas definidas pelo usuário. Essas funções são escritas em linguagens de programação, como PLSQL , Java e C, e podem ser utilizados como funções analíticas ou agregados em visões materializadas. Consulte o Guia de Desenvolvedores de Cartuchos de Dados de Banco de Dados Oracle para obter mais informações sobre sintaxe e restrições. As vantagens dessas funções são: Funções altamente complexas ca N seja programado usando uma linguagem totalmente processual. Maior escalabilidade do que outras técnicas quando as funções definidas pelo usuário são programadas para processamento paralelo. Os tipos de dados de objetos podem ser processados. Como um exemplo simples de uma função agregada definida pelo usuário, considere a estatística de inclinação. Este cálculo mede se um conjunto de dados tiver uma distribuição desequilibrada sobre o seu significado. Ele irá dizer se uma das colunas da distribuição é significativamente maior do que a outra. Se você criou um agregado definido pelo usuário chamado udskew e aplicou-o aos dados de limite de crédito no exemplo anterior, a instrução SQL e os resultados podem parecer assim: antes de criar funções agregadas definidas pelo usuário, você deve considerar se suas necessidades podem ser atendidas Em SQL normal. Muitos cálculos complexos são possíveis diretamente no SQL, particularmente usando a expressão CASE. Permanecer com SQL regular permitirá um desenvolvimento mais simples, e muitas operações de consulta já estão bem paralelizadas em SQL. Mesmo o exemplo anterior, a estatística de inclinação, pode ser criada usando padrão, embora longo, SQL. CASO Expressões A Oracle agora oferece instruções de CASE simples e procuradas. As declarações CASE são semelhantes em propósito para a declaração DECODE, mas oferecem mais flexibilidade e poder lógico. Eles também são mais fáceis de ler do que as declarações DECODE tradicionais e oferecem um melhor desempenho também. Eles são comumente usados ao romper categorias em baldes como a idade (por exemplo, 20-29, 30-39 e assim por diante). A sintaxe para instruções CASE simples é: teste de expressões CASE simples se o valor expr igual a comparisonexpr. A sintaxe para as afirmações CASE pesquisadas é: Você pode usar qualquer tipo de condição em uma expressão CASE pesquisada, e não apenas em um teste de igualdade. Você pode especificar apenas 255 argumentos e cada QUATRO. Então, o par conta como dois argumentos. Para evitar exceder esse limite, você pode aninhar as expressões CASE para que o returnexpr em si seja uma expressão CASE. Exemplo 21-21 CASO Suponha que você desejasse encontrar o salário médio de todos os funcionários da empresa. Se um salário de funcionários for inferior a 2000, você deseja que a consulta use 2000 em vez disso. Sem uma declaração CASE, você pode optar por escrever esta consulta da seguinte maneira: Observe que isso é executado contra o esquema de exemplo hr. Nisto, foo é uma função que retorna sua entrada se a entrada for maior que 2000 e retorna 2000 de outra forma. A consulta tem implicações de desempenho porque precisa invocar uma função para cada linha. Escrever funções personalizadas também pode adicionar à carga de desenvolvimento. Usando expressões CASE no banco de dados sem PLSQL, esta consulta pode ser reescrita como: Usar uma expressão CASE permite evitar o desenvolvimento de funções personalizadas e também pode ser mais rápido. Exemplo 21-22 CASO para agregação de subconjuntos independentes Usando CASE dentro de funções agregadas é uma maneira conveniente de realizar agregados em vários subconjuntos de dados quando um GRUPO GRUPO simples não será suficiente. Por exemplo, o exemplo anterior poderia ter incluído múltiplas colunas AVG em sua lista SELECT, cada uma com sua própria expressão CASE. Nós poderíamos ter uma consulta para encontrar o salário médio para todos os funcionários nas gamas salariais de 0-2000 e 2000-5000. Pareceria: Embora essa consulta coloca os agregados de dados de subconjuntos independentes em colunas separadas, adicionando uma expressão CASE à cláusula GROUP BY, podemos exibir os agregados como as linhas de uma única coluna. A próxima seção mostra a flexibilidade desta abordagem com duas abordagens para criar histogramas com CASE. Criando histogramas com baldes definidos pelo usuário Você pode usar a instrução CASE quando quiser obter histogramas com baldes definidos pelo usuário (tanto no número de baldes quanto na largura de cada balde). A seguir estão dois exemplos de histogramas criados com instruções CASE. No primeiro exemplo, os totais do histograma são mostrados em várias colunas e uma única linha é retornada. No segundo exemplo, o histograma é mostrado com uma coluna de rótulo e uma única coluna para totais, e várias linhas são retornadas. Exemplo 21-23 Histograma Exemplo 1 Exemplo 21-24 Histograma Exemplo 2 Densificação de Dados para Relatórios Os dados são normalmente armazenados em forma esparsa. Ou seja, se nenhum valor existe para uma determinada combinação de valores de dimensão, nenhuma linha existe na tabela de fatos. No entanto, você pode querer ver os dados em forma densa, com linhas para todos os valores de cota de combinação exibidos mesmo quando não existem dados de fato para eles. Por exemplo, se um produto não vendeu durante um determinado período de tempo, você ainda pode querer ver o produto para esse período de tempo com zero valor de vendas ao lado dele. Além disso, os cálculos das séries temporais podem ser realizados com maior facilidade quando os dados são densos ao longo da dimensão do tempo. Isso ocorre porque os dados densos preencherão um número consistente de linhas para cada período, o que, por sua vez, torna simples usar as funções de janela analítica com deslocamentos físicos. A densificação de dados é o processo de conversão de dados dispersos em uma forma densa. Para superar o problema de sparsity, você pode usar uma junção externa particionada para preencher as lacunas em uma série temporal ou qualquer outra dimensão. Tal associação amplia a sintaxe de associação externa convencional aplicando a junção externa a cada partição lógica definida em uma consulta. O Oracle logicamente particiona as linhas em sua consulta com base na expressão que você especificou na cláusula PARTITION BY. O resultado de uma junção externa particionada é uma UNION das junções externas de cada uma das partições na tabela logicamente particionada com a tabela do outro lado da junção. Observe que você pode usar esse tipo de associação para preencher as lacunas em qualquer Dimensão, não apenas a dimensão do tempo. A maioria dos exemplos aqui se concentra na dimensão do tempo porque é a dimensão mais usada como base para comparações. Sintaxe de associação de partição A sintaxe para associação externa particionada estende a cláusula ANSI SQL JOIN com a frase PARTITION BY seguida de uma lista de expressões. As expressões na lista especificam o grupo ao qual a associação externa é aplicada. As seguintes são as duas formas de sintaxe normalmente usadas para junção externa particionada: Observe que FULL OUTER JOIN não é suportado com uma junção externa particionada. Exemplo de Dados Esparsos Uma situação típica com uma dimensão esparsa é mostrada no exemplo a seguir, que calcula as vendas semanais e as vendas acumuladas no acumulado do ano para o produto Bounce nas semanas 20 a 30 em 2000 e 2001: neste exemplo, nós Esperaria 22 linhas de dados (11 semanas a cada 2 anos) se os dados fossem densos. No entanto, obtemos apenas 18 linhas porque as semanas 25 e 26 estão faltando em 2000 e as semanas 26 e 28 em 2001. Preenchimento de lacunas em dados Podemos tirar dados escassos da consulta anterior e fazer uma junção externa particionada com um denso conjunto de tempo dados. Na consulta a seguir, alias nossa consulta original como v e selecionamos dados da tabela de horários, que nós alias como t. Aqui, recuperamos 22 linhas porque não há lacunas na série. As quatro linhas adicionadas possuem 0 como seu valor de vendas definido como 0 usando a função NVL. Observe que nesta consulta, uma condição WHERE foi colocada por semanas entre 20 e 30 na visualização em linha para a dimensão temporal. Isso foi introduzido para manter o conjunto de resultados pequeno. Lacunas de preenchimento em duas dimensões Os dados de N-dimensional geralmente são exibidos como uma aba cruzada bidimensional densa de (n - 2) dimensões da página. Isso requer que todos os valores de dimensão para as duas dimensões que aparecem na aba cruzada sejam preenchidos. O seguinte é outro exemplo em que a capacidade de junção externa particionada pode ser usada para preencher as lacunas em duas dimensões: nessa consulta, a cláusula de factoring WITH subquery A v1 resume os dados de vendas no produto, no país e no nível do ano. Esse resultado é esparso, mas os usuários podem querer ver todas as combinações país, ano para cada produto. Para conseguir isso, tomamos cada partição de v1 com base nos valores dos produtos e junte-a externamente na dimensão do país primeiro. Isso nos dará todos os valores do país para cada produto. Em seguida, levamos esse resultado e particionamos nos valores do produto e do país e, em seguida, juntamos-o na dimensão do tempo. Isso nos dará todos os valores de tempo para cada combinação de produto e país. Lacunas de preenchimento em uma tabela de inventário Uma tabela de estoque normalmente rastreia a quantidade de unidades disponíveis para vários produtos. Esta tabela é esparsa: apenas armazena uma linha para um produto quando há um evento. Para uma tabela de vendas, o evento é uma venda, e para a tabela de inventário, o evento é uma alteração na quantidade disponível para um produto. Por exemplo, considere a seguinte tabela de inventário: A tabela de inventário agora possui as seguintes linhas: Para fins de relatório, os usuários podem querer ver esses dados de inventário de forma diferente. Por exemplo, eles podem querer ver todos os valores de tempo para cada produto. Isso pode ser feito usando a junção externa particionada. Além disso, para as linhas recém-inseridas de períodos de tempo faltantes, os usuários podem querer ver os valores da quantidade de unidades de coluna a serem transferidas do período de tempo existente mais recente. O último pode ser realizado usando o valor LASTVALUE da função de janela analítica. Aqui está a consulta e a saída desejada: A consulta interna computa uma junção externa particionada no tempo dentro de cada produto. A consulta interna densifica os dados na dimensão do tempo (o que significa que a dimensão do tempo agora terá uma linha para cada dia da semana). No entanto, a quantidade de coluna de medida terá nulos para as linhas recentemente adicionadas (veja a saída na quantidade de coluna nos seguintes resultados. A consulta externa usa a função analítica LASTVALUE. Aplicando esta função, particiona os dados por produto e ordena os dados no Coluna de dimensão do tempo (timeid). Para cada linha, a função encontra o último valor não nulo na janela devido à opção IGNORE NULLS. Que você pode usar com LASTVALUE e FIRSTVALUE. Vemos a saída desejada na quantidade repetida da coluna em A seguinte saída: Computação de valores de dados para preencher lacunas. Exemplos na seção anterior ilustram como usar a junção externa particionada para preencher lacunas em uma ou mais dimensões. No entanto, os conjuntos de resultados produzidos por junção externa particionada possuem valores nulos para colunas que não estão incluídas em A lista PARTITION BY. Normalmente, estas são colunas de medida. Os usuários podem usar funções SQL analíticas para substituir esses valores nulos por um valor não nulo. Por exemplo, o seguinte q Utile calcula totais mensais para produtos de 64MB de cartão de memória e discos DVD-R (ID de produto 122 e 136) para o ano 2000. Ele usa junção externa particionada para densificar dados para todos os meses. Para os meses que faltam, ele usa a função SQL analítica AVG para calcular as vendas e as unidades como a média dos meses em que o produto foi vendido. Se estiver trabalhando no SQLPlus, os dois comandos a seguir envolverão os cabeçalhos das colunas para maior legibilidade dos resultados: os Cálculos da Série de Tempo na Densificação de Dados Densificados não são apenas para fins de relatório. Também permite certos tipos de cálculos, especialmente cálculos de séries temporais. Os cálculos da série temporal são mais fáceis quando os dados são densos ao longo da dimensão do tempo. Os dados densos têm um número consistente de linhas para cada período de tempo, o que, por sua vez, torna simples usar funções de janela analítica com deslocamentos físicos. Para ilustrar, primeiro façamos o exemplo de preenchimento de lacunas em dados. E vamos adicionar uma função analítica a essa consulta. Na seguinte versão aprimorada, calculamos as vendas semanais acumuladas ao longo do ano, ao lado das vendas semanais. Os valores NULL que a junção externa particionada se inserem ao fazer as séries temporais densas são tratados de maneira usual: a função SUM os trata como 0s. Comparação período a período para um nível de tempo: Exemplo Como usamos esse recurso para comparar valores em períodos de tempo Especificamente, como calculamos uma comparação de vendas ano a ano no nível da semana. A seguinte consulta retorna na mesma linha , Para cada produto, as vendas do ano até à data para cada semana de 2001 com a de 2000. Observe que neste exemplo começamos com uma cláusula WITH. Isso melhora a legibilidade da consulta e nos permite focar a união externa particionada. Se estiver trabalhando no SQLPlus, o comando a seguir envolverá os cabeçalhos das colunas para maior legibilidade dos resultados: Na cláusula FROM da visualização em linha densesales. Usamos uma junção externa particionada de vista agregada v e exibição de tempo t para preencher lacunas nos dados de vendas ao longo da dimensão do tempo. A saída da união externa particionada é então processada pela função analítica SUM. OVER para calcular as vendas semanais do ano até à data (a coluna weeklyytdsales). Assim, a vista densesales calcula os dados de vendas do ano até à data para cada semana, incluindo aqueles que faltam na visão agregada s. A exibição em linha yearoveryearsales, em seguida, calcula ano a ano as vendas semanais do ano até à data usando a função LAG. A função LAG rotulada weeklyytdsalesprioryear especifica uma cláusula PARTITION BY que combina linhas para a mesma semana dos anos 2000 e 2001 em uma única partição. Em seguida, passamos um deslocamento de 1 para a função LAG para obter as vendas do ano semanal para o ano anterior. O bloco de consulta mais externo seleciona dados de yearoveryearsales com a condição yr 2001. e, portanto, a consulta retorna, para cada produto, é semanal Vendas no acumulado do ano nas semanas especificadas dos anos de 2001 e 2000. Comparação Período-Período para vários níveis de tempo: Exemplo Enquanto o exemplo anterior nos mostra uma maneira de criar comparações para um único nível de tempo, seria ainda mais Útil para lidar com vários níveis de tempo em uma única consulta. Por exemplo, podemos comparar as vendas em relação ao período anterior nos níveis de ano, trimestre, mês e dia. Como podemos criar uma consulta que realiza uma comparação de ano a ano sobre as vendas acumuladas em todos os níveis de nossa hierarquia de tempo. Vamos realizar várias etapas para executar esta tarefa. O objetivo é uma única consulta com comparações ao nível do dia, semana, mês, trimestre e ano. Os passos são os seguintes: criaremos uma visão chamada cubeprodtime. Que possui um cubo hierárquico de vendas agregado em tempos e produtos. Então, criaremos uma visão da dimensão do tempo para usar como uma ponta do cubo. A borda do tempo, que contém um conjunto completo de datas, será particionada externa unida aos dados esparsos na vista cubeprodtime. Finalmente, para o máximo desempenho, criaremos uma visão materializada, mvprodtime. Construído usando a mesma definição como cubeprodtime. Para obter mais informações sobre cubos hierárquicos, consulte o Capítulo 20, SQL para agregação em data warehouses. A visualização materializada é definida na Etapa 1 na seção a seguir. Passo 1 Crie a visão do cubo hierárquico A visualização materializada mostrada no seguinte pode existir no seu sistema se não, crie-o agora. Se você deve gerá-lo, observe que limitamos a consulta apenas a dois produtos para manter o tempo de processamento curto: porque essa visão é limitada a dois produtos, ele retorna apenas mais de 2200 linhas. Observe que a coluna HierarchicalTime contém representações de seqüência de tempo de todos os níveis da hierarquia de tempo. A expressão CASE usada para a coluna HierarchicalTime anexa um marcador (0, 1.) a cada string de data para indicar o nível de tempo do valor. A 0 representa o nível do ano, 1 é quarto, 2 meses e 3 é o dia. Observe que a cláusula GROUP BY é um ROLLUP concatenado que especifica a hierarquia de rollup para o tempo e as dimensões do produto. A cláusula GROUP BY é o que determina o conteúdo do cubo hierárquico. Passo 2 Crie a visualização edgetime, que é um conjunto completo de valores de data, o edgetime é a fonte para preencher intervalos de tempo no cubo hierárquico usando uma junção externa particionada. A coluna HierarchicalTime em edgetime será usada em uma junção particionada com a coluna HierarchicalTime na vista cubeprodtime. A seguinte declaração define edgetime: Etapa 3 Crie a visualização materializada mvprodtime para suportar um desempenho mais rápido. A definição de exibição materializada é uma duplicata da visão que o cubeprodtime definiu anteriormente. Como é uma consulta duplicada, as referências ao cubeprodtime serão reescritas para usar a visão materializada do mvprodtime. Os seguintes materiais já podem existir no seu sistema, caso contrário, crie-o agora. Se você deve gerá-lo, observe que limitamos a consulta apenas a dois produtos para manter o tempo de processamento curto. Passo 4 Crie a consulta de comparação Nós estabelecemos o cenário para a nossa consulta de comparação. Podemos obter cálculos de comparação de período a período em todos os níveis de tempo. Ele requer a aplicação de funções analíticas a um cubo hierárquico com dados densos ao longo da dimensão temporal. Alguns dos cálculos que podemos alcançar para cada nível de tempo são: Soma das vendas para o período anterior em todos os níveis de tempo. Variação nas vendas ao longo do período anterior. Soma das vendas no mesmo período de um ano atrás em todos os níveis de tempo. Variação nas vendas em relação ao mesmo período do ano passado. O seguinte exemplo executa todos os quatro desses cálculos. Ele usa uma junção externa particionada das vistas cubeprodtime e edgetime para criar uma visão em linha de dados densos chamados densecubeprodtime. A consulta então usa a função LAG da mesma maneira que o exemplo anterior de nível único. A cláusula WHERE externa especifica o tempo em três níveis: os dias de agosto de 2001, todo o mês e todo o terceiro trimestre de 2001. Observe que as últimas duas linhas dos resultados contêm as agregações de nível de mês e quarto. Observe que fazer Os resultados são mais fáceis de ler se você estiver usando o SQLPlus, os cabeçalhos das colunas devem ser ajustados com os seguintes comandos. The commands will fold the column headings to reduce line length: Here is the query comparing current sales to prior and year ago sales: The first LAG function ( salespriorperiod ) partitions the data on gidp. cat. subcat. prod. gidt and orders the rows on all the time dimension columns. It gets the sales value of the prior period by passing an offset of 1. The second LAG function ( salessameperiodprioryear ) partitions the data on additional columns qtrnum. monnum. and daynum and orders it on yr so that, with an offset of 1, it can compute the year ago sales for the same period. The outermost SELECT clause computes the variances. Creating a Custom Member in a Dimension: Example In many OLAP tasks, it is helpful to define custom members in a dimension. For instance, you might define a specialized time period for analyses. You can use a partitioned outer join to temporarily add a member to a dimension. Note that the new SQL MODEL clause is suitable for creating more complex scenarios involving new members in dimensions. See Chapter 22, SQL for Modeling for more information on this topic. As an example of a task, what if we want to define a new member for our time dimension We want to create a 13th member of the Month level in our time dimension. This 13th month is defined as the summation of the sales for each product in the first month of each quarter of year 2001. The solution has two steps. Note that we will build this solution using the views and tables created in the prior example. Two steps are required. First, create a view with the new member added to the appropriate dimension. The view uses a UNION ALL operation to add the new member. To query using the custom member, use a CASE expression and a partitioned outer join. Our new member for the time dimension is created with the following view: In this statement, the view timec is defined by performing a UNION ALL of the edgetime view (defined in the prior example) and the user-defined 13th month. The gidt value of 8 was chosen to differentiate the custom member from the standard members. The UNION ALL specifies the attributes for a 13th month member by doing a SELECT from the DUAL table. Note that the grouping id, column gidt. is set to 8, and the quarter number is set to 5. Then, the second step is to use an inline view of the query to perform a partitioned outer join of cubeprodtime with timec. This step creates sales data for the 13th month at each level of product aggregation. In the main query, the analytic function SUM is used with a CASE expression to compute the 13th month, which is defined as the summation of the first months sales of each quarter. The SUM function uses a CASE to limit the data to months 1, 4, 7, and 10 within each year. Due to the tiny data set, with just 2 products, the rollup values of the results are necessarily repetitions of lower level aggregations. For more realistic set of rollup values, you can include more products from the Game Console and Y Box Games subcategories in the underlying materialized view. Scripting on this page enhances content navigation, but does not change the content in any way. The Matrix and Solving Systems with Matrices This section covers: Introduction to the Matrix A matrix (plural matrices ) is sort of like a box of information where you are keeping track of things both right and left ( columns ), and up and down ( rows ). Usually a matrix contains numbers or algebraic expressions . You may have heard matrices called arrays . especially in computer science. As an example, if you had three sisters, and you wanted an easy way to store their age and number of pairs of shoes, you could store this information in a matrix. The actual matrix is inside and includes the brackets: Matrices are called multi-dimensional since we have data being stored in different directions in a grid. The dimensions of this matrix are 2 x 3 or 2 by 3, since we have 2 rows and 3 columns. (You always go down first, and then over to get the dimensions of the matrix). Again, matrices are great for storing numbers and variables and also great for solving systems of equations, which well see later. Each number or variable inside the matrix is called an entry or element . and can be identified by subscripts . For example, for the matrix above, Brett would be identified as , since its on the 2 nd row and its the 1 st entry. Adding and Subtracting Matrices Lets look at a matrix that contains numbers and see how we can add and subtract matrices. Lets say youre in avid reader, and in June, July, and August you read fiction and non-fiction books, and magazines, both in paper copies and online. You want to keep track of how many different types of books and magazines you read, and store that information in matrices. Here is that information, and how it would look in matrix form: We can add matrices if the dimensions are the same since the three matrices are all 3 by 2, we can add them. For example, if we wanted to know the total number of each type of bookmagazine we read, we could add each of the elements to get the sum: Thus we could see that we read 6 paper fiction, 9 online fiction, 6 paper non-fiction, 5 online non-fiction books, and 13 paper and 14 online magazines. We could also subtract matrices this same way. If we wanted to see how many book and magazines we would have read in August if we had doubled what we actually read, we could multiply the August matrix by the number 2. This is called matrix scalar multiplication a scalar is just a single number that we multiply with every entry. Note that this is not the same as multiplying 2 matrices together (which we8217ll get to next): Multiplying Matrices Multiplying matrices is a little trickier. First of all, you can only multiply matrices if the dimensions 8220match8221 the second dimension (columns) of the first matrix has to match the first dimension (rows) of the second matrix . or you cant multiply them. Think of it like the inner dimensions have to match . and the resulting dimensions of the new matrix are the outer dimensions . Heres an example of matrices with dimensions that would work: Notice how the middle or 8220inner8221 dimensions of the first matrices have to be the same (in this case, 2), and the new matrix has the outside or 8220outer8221 dimensions of the first two matrices (3 by 5). Now, lets do a real-life example to see how the multiplication works . Lets say we want to find the final grades for 3 girls, and we know what their averages are for tests, projects, homework, and quizzes. We also know that tests are 40 of the grade, projects 15, homework 25, and quizzes 20. Heres the data we have: Lets organize the following data into two matrices, and perform matrix multiplication to find the final grades for Alexandra, Megan, and Brittney. To do this, you have to multiply in the following way: Just remember when you put matrices together with matrix multiplication , the columns (what you see across) on the first matrix have to correspond to the rows down on the second matrix . You should end up with entries that correspond with the entries of each row in the first matrix. For example, with the problem above, the columns of the first matrix each had something to do with Tests, Projects, Homework, and Quizzes (grades). The row down on the second matrix each had something to do with the same four items (weights of grades). But then we ended up with information on the three girls (rows down on the first matrix). So Alexandra has a 90, Megan has a 77, and Brittney has an 87 . See how cool this is Matrices are really useful for a lot of applications in real life Now lets do another example let8217s multiply the following matrices: Dont worry probably most of the time youll be doing matrix multiplication will be in the calculator Oh, one more thing Remember that multiplying matrices is not commutative (order makes a difference), but is associative (you can change grouping of matrices when you multiply them). Multiplying matrices is also distributive (you can push through a matrix through parentheses), as long as the matrices have the correct dimensions to be multiplied. Matrices in the Graphing Calculator The TI graphing calculator is great for matrix operations Here are some basic steps for storing, multiplying, adding, and subtracting matrices: (Note that you can also enter matrices using ALPHA ZOOM and the arrow keys in the newer graphing calculators.) Well learn other ways to use the calculator with matrices a little later. Determinants, the Matrix Inverse, and the Identity Matrix Soon we will be solving Systems of Equations using matrices, but we need to learn a few mechanics first Most square matrices (same dimension down and across) have what we call a determinant . which well need to get the multiplicative inverse of that matrix. The inverse of a matrix is what we multiply that square matrix by to get the identity matrix. Well use the inverses of matrices to solve Systems of Equations the inverses will allow us to get variables by themselves on one side (like regular algebra). Youll solve these mainly by using your calculator . but youll also have to learn how to get them by hand. Note that the determinant of a matrix can be designated by (det left text right) or (left text right), and the inverse of a matrix by ( ). Lets do some examples and first get the determinant of matrices (which we can get easily on a calculator). The determinant is always just a scalar (number), and you8217ll see it with two lines around the matrix: Now lets use the determinant to get the inverse of a matrix . Well only work with 2 by 2 matrices, since youll probably be able to use the calculator for larger matrices. Note again that only square matrices have inverses . but there are square matrices that dont have one (when the determinant is 0): When you multiply a square matrix with an identity matrix, you just get that matrix back: . Think of an identity matrix like 1 in regular multiplication (the multiplicative identity), and the inverse matrix like a reciprocal (the multiplicative inverse). Solving Systems with Matrices Why are we doing all this crazy math Because we can solve systems with the inverse of a matrix . since the inverse is sort of like dividing to get the variables all by themselves on one side. To solve systems with matrices, we use . Here is why, if youre interested in the theory (the column on the right provides an example with regular multiplication). ( I is the identity matrix.) Lets take the system of equations that we worked with earlier and show that it can be solved using matrices: Oh, and theres another way to solve these in your calculator, but your teacher may not tell you. Im not going to go into the details, but its using a method called reduced row echelon form . where we can put everything in one matrix (called an augmented matrix ). Lets try this for the following matrix: A little easier, right Solving Word Problems With Matrices Now that we know how to solve systems using matrices, we can solve them so much faster Lets do a couple of pure matrices problems, and then more systems problems :). Matrix Multiplication Problem (a) When we multiply a matrix by a scalar (number), we just multiply all elements in the matrix by that number. So 2P Matrix Equation Problem: This ones a little trickier, since it doesnt really look like a systems problem, but you solve it the same way: Solve the matrix equation for X ( X will be a matrix): Lets add the second matrix to both sides, to get X and its coefficient matrix alone by themselves. Then well divide by the matrix in front of X . Watch the order when we multiply by the inverse (matrix multiplication is not commutative), and thank goodness for the calculator Matrix Multiplication Word Problem: The following matrix consists of a shoe stores inventory of flip flops, clogs, and Mary Janes in sizes small, medium, and large: The store wants to know how much their inventory is worth for all the shoes. How should we set up the matrix multiplication to determine this the best way The trick for these types of problems is to line up what matches (flip flops, clogs, and Mary Janes), and that will be in the middle when we multiply. This way our dimension will line up. Another way to look at it is we need to line up what goes across the first matrix with what goes down the second matrix, and well end up with what goes down the first matrix for these types of problems. So our matrix multiplication will look like this, even though our tables look a little different (I did this on a calculator): So well have 1050 worth of small shoes, 2315 worth of medium shoes, and 1255 worth of large shoes for a total of 4620 . Another Matrix Multiplication Word Problem: A nut distributor wants to know the nutritional content of various mixtures of almonds, cashews, and pecans. Her supplier has provided the following nutrition information: Her first mixture, a protein blend, consists of 6 cups of almonds, 3 cups of cashews, and 1 cup of pecans. Her second mixture, a low fat mix, consists of 3 cups of almonds, 6 cups of cashews, and 1 cup of pecans. Her third mixture, a low carb mix consists of 3 cups of almonds, 1 cup of cashews, and 6 cups of pecans. Determine the amount of protein, carbs, and fats in a 1 cup serving of each of the mixtures. Sometimes we can just put the information we have into matrices to sort of see what we are going to do from there. It makes sense to put the first group of data into a matrix with Almonds, Cashews, and Pecans as columns, and then put the second group of data into a matrix with information about Almonds, Cashews, and Pecans as rows. This way the columns of the first matrix lines up with the rows of the second matrix, and we can perform matrix multiplication. This way we get rid of the number of cups of Almonds, Cashews, and Pecans . which we dont need. So here is the information we have in tablematrix form: Then we can multiply the matrices (we can use a graphing calculator) since we want to end up with the amount of Protein, Carbs, and Fat in each of the mixtures . The product of the matrices consists of rows of Protein, Carbs, and Fat . and columns of the Protein, Low Fat, and Low Carb mixtures : But we have to be careful, since these amounts are for 10 cups (add down to see well get 10 cups for each mixture in the second matrix above). Also, notice how the cups unit canceled out when we did the matrix multiplication (gramscup time cups grams). So to get the answers, we have to divide each answer by 10 to get grams per cup . So the numbers in bold are our answers: Matrix Word Problem when Tables are not Given: Sometimes you8217ll get a matrix word problem where just numbers are given these are pretty tricky. Here is one: An outbreak of Chicken Pox hit the local public schools. Approximately 15 of the male and female juniors and 25 of the male and female seniors are currently healthy, 35 of the male and female juniors and 30 of the male and female seniors are currently sick, and 50 of the male and female juniors and 45 of the male and female seniors are carriers of Chicken Pox. There are 100 male juniors, 80 male seniors, 120 female juniors, and 100 female seniors. Using two matrices and one matrix equation, find out how many males and how many females (dont need to divide by class) are healthy, sick, and carriers. The best way to approach these types of problems is to set up a few manual calculations and see what were doing. For example, to find out how many healthy males we would have, wed set up the following equation and do the calculation. 15(100) .25(80) 35. Likewise, to find out how many females are carriers . we can calculate. 50(120) .45(100) 105. We can tell that this looks like matrix multiplication . And since we want to end up with a matrix that has males and females by healthy, sick and carriers, we know it will be either a 2 x 3 or a 3 x 2. But since we know that we have both juniors and seniors with males and females, the first matrix will probably be a 2 x 2. That means, in order to do matrix multiplication, the second matrix that holds the s of students will have to be a 2 x 3, since there are 3 types of students, healthy (H), sick (S), and carriers (C). Notice how the percentages in the rows in the second matrix add up to 100. Also notice that if we add up the number of students in the first matrix and the last matrix, we come up with 400. So we can come up with the following matrix multiplication: So there will be 35 healthy males, 59 sick males, and 86 carrier males, 43 healthy females, 72 sick females, and 95 carrier females. Pretty clever Matrix Multiplication when Diagonals are Answers: The first table below show the points awarded by judges at a state fair for a crafts contest for Brielle, Brynn, and Briana. The second table shows the multiplier used for the degree of difficulty for each of the pieces the girls created. Find the total score for each of the girls in this contest. This ones a little trickier since it looks like we have two 3 x 2 matrices (tables), but we only want to end up with three answers . the total score for each of the girls. If we were to do the matrix multiplication using the two tables above, we would get: Hmm. this is interesting we end up with a matrix with the girlss names as both rows and columns. It turns out that we have extraneous information in this matrix we only need the information where the girls names line up. So we only look at the diagonal of the matrix to get our answers: Brielle had 86.8 points . Brynn 79.2 points . and Briana 110 points . What we really should have done with this problem is to use matrix multiplication separately for each girl for example, for Brielle, we should have multiplied and so on. Oh well, no harm done and now youll know what to do if you see these types of matrices problems. Using Matrices to Solve Systems Solve these word problems with a system of equations. Write the system, the matrix equations, and solve: Finding the Numbers Word Problem: The sum of three numbers is 26. The third number is twice the second, and is also 1 less than 3 times the first. What are the three numbers Lets translate word-for-word from English to Math that we learned in the Algebra Word Problem Section here . Note that, in the last equation, one less than means put the 1 at the end (do this with real numbers to see why). So we need to move things around so that all the variables (with coefficients in front of them) are on the left, and the numbers are on the right . (It doesn8217t matter which side just watch for negatives). If we just have the variable in the equation, we put a 1 in the matrix if we dont have a variable or a constant (number), we put a 0 in the matrix. So we get: and in matrix form: Putting the matrices in the calculator, and using the methods from above, we get: So the numbers are 5 . 7. and 14 . Much easier than figuring it out by hand A Florist Must Make 5 Identical Bridesmaid Bouquets Systems Problem Heres a problem from the Systems of Linear Equations and Word Problems Section we can see how much easier it is to solve with a matrix. A florist is making 5 identical bridesmaid bouquets for a wedding. She has 610 to spend (including tax) and wants 24 flowers for each bouquet. Roses cost 6 each, tulips cost 4 each, and lilies cost 3 each. She wants to have twice as many roses as the other 2 flowers combined in each bouquet. How many roses, tulips, and lilies are in each bouquet Lets look at the question that is being asked and define our variables: Let r the number of roses, t the number of tulips, and l the number of lilies. So lets put the money terms together, and also the counting terms together: Now lets put the system in matrices (lets just use one matrix) and on the calculator: So for all the bouquets, well have 80 roses, 10 tulips, and 30 lilies. An Input Output Problem Input-output problems are seen in Economics . where we might have industries that produce for consumers, but also consume for themselves. An application of matrices is used in this input-output analysis, which was first proposed by Wassily Leontief in fact he won the Nobel Prize in economics in 1973 for this work. We can express the amounts (proportions) the industries consume in matrices, such as in the following problem: The following coefficient matrix, or input-output matrix, shows the values of energy and manufacturing consumed internally needed to produce 1 of energy and manufacturing, respectively. In other words, of the value of energy produced ( x for energy, y for manufacturing), 40 percent of it, or .40 x pays to produce internal energy, and 25 percent of it, or .25 x pays for internal manufacturing. Of the value of the manufacturing produced. 25 y pays for its internal energy and .10 y pays for manufacturing consumed internally. The inputs are the amount used in production, and the outputs are the amounts produced. (a) If the capacity of energy production is 15 million and the capacity of manufacturing production is 20 million, how much of each is consumed internally for capacity production (b) How much energy and manufacturing must be produced to have 8 million worth of energy and 5 million worth of manufacturing available for consumer use (a) If production capacities are 15 million for energy and 20 million for manufacturing, the amount consumed internally is . So 11 million of energy is consumed internally and 5.75 million of manufacturing is consumed internally. This makes sense, for example, since were multiplying the proportion of energy consumed internally (.4) by the production capacity for energy (15 million) and adding that to the proportion of energy needed for internal manufacturing (.25) by the production capacity of manufacturing (20 million) to get the total dollar amount of energy needed or consumed internally (11 million). Then we do the same for manufacturing. (b) The amount of energy and manufacturing to be produced to have 8 million worth of energy and 5 million worth of manufacturing available for consumer (non-internal) use is solved using the following equation (we want what8217s 8220left over8221 after the internal consumption, so it makes sense): . To get , we can use the formula . So the two industries must produce 17.7 million worth of energy and 10.5 million worth of manufacturing, respectively. Cramer8217s Rule Sometimes youll have to learn Cramers Rule . which is another way to solve systems with matrices. Cramers Rule was named after the Swiss mathematician Gabriel Cramer, who also did a lot of other neat stuff with math. Cramers rule is all about getting determinants of the square matrices that are used to solve systems. Its really not too difficult it can just be a lot of work, so again, Ill take the liberty of using the calculator to do most of the work Number of Solutions when Solving Systems with Matrices Most systems problems that youll deal with will just have one solution. (These equations are called independent or consistent). But, like we learned in the Systems of Linear Equations and Word Problems Section here . sometimes we have systems where we either have no solutions or an infinite number of solutions. Without going too much into Geometry, lets look at what it looks like when three systems (each system looks like a plane or a piece of paper) have an infinite number of solutions . no solutions . and one solution . respectively: Systems that have an infinite number of solution s (called dependen t or coincident ) will have two equations that are basically the same. One row of the coefficient matrix (and the corresponding constant matrix) is a multiple of another row. Then its like youre trying to solve a system with only two equations, but three unknowns. Systems with no solutions (called inconsistent ) will have one row of the coefficient matrix a multiple of another, but the coefficient matrix will not have this. So a system that has no solutions may look like this: When you try to these types of systems in your calculator (using matrices), youll get an error since the determinant of the coefficient matrix will be 0. This is called a singular matrix and the calculator will tell you so: For the system with no solutions . youll get this, where you can see that you still dont have an identity matrix, and 0 can never equal 1 from the last row: Learn these rules, and practice, practice, practice Use the MathType keyboard to enter a Limit problem, and then click on Submit (the arrow to the right of the problem) to solve the problem. You can also click on the 3 dots in the upper right hand corner to drill down for example problems. If you click on 8220Tap to view steps, you will go to the Mathway site, where you can register for the full version (steps included) of the software. You can even get math worksheets. You can also go to the Mathway site here. where you can register, or just use the software for free without the detailed solutions. There is even a Mathway App for your mobile device. Enjoy 183 thoughts on ldquo The Matrix and Solving Systems with Matrices rdquo This is great, and also can you show when matrices are used in repetition, like occurrence over a few days I love this website, I will have to bookmark it (--) Thanks so much for writing. Good point 8211 I just added this in the Matrix Multiplication section: Remember that multiplying matrices is not commutative (order makes a difference), but is associative (you can change grouping of matrices when you multiply them). Multiplying matrices is also distributive (you can push through a matrix through parentheses), as long as the matrices have the correct dimension to be multiplied. So if you have matrices in repetition, you can multiply the first 2, then the 3rd, or the second 2 first. You cannot change the order of multiplying though. Does this make sense Lisa Can u help me solve this problem Mr. Tan want to support his wife on her dietary plan. He decided to investigate the carbohydrate content of the vegetable they plant. Together. i cup of raw cabbage, 5 raw cauliflowers, and 1 cup of raw tomatoes contain 12 gram of carbohydrates. One cup of raw cabbage and 6 cauliflowers have one-half the carbohydrates of 1 cup of raw tomatoes. One cup each of raw cabbage and raw tomatoes has 3 times the carbohydrate content of 6 raw cauliflowers. Find the number of grams of carbohydrates in the given portion size of each vegetable Thanks for the problem I set it up with the following equations: r 6c t 12 (I think for it to work, you meant 6 raw cauliflowers in the 3rd sentence) r 6c .5t r t 3(6)c Then I put the following matrix in my calculator and used RREF: 1 6 1 12 1 6 -.5 0 to get 1 cup of raw cabbage, 12 of a cauliflower, and 8 cups of tomatoes. 1 -18 1 0 Does this make sense Lisa thank you so much for helping me out..i8217ve really lost it try to do this problem..thank you again. ). hehe B2by2 matriz a1 b1 c2 d1 The question asks me to find A in the equation B(IA-1)I A-1 is the inverse of A and the I is the identity matrix. Can you help me out Thanks for writing I just 8220divided8221 by B (using inverse matrix) and then subtracted the identity matrix and got A-1 -2 1 2 -2. Then took the inverse of that and got A -1, -12, -1, -1. (a b d). Does that make sense Lisa A chemical manufacturer wants to lease a fleet of 24 railroad tank cars with a combined carrying capacity of 420.000 gallons. Tank cars with three different carrying capacities are available. 7.000 gallons, 14.000 gallons, and 28.000 gallons. How many each type of tank car should be leased. use gaussian elimination method to solve it. please any help me out to solve me this problem I am having issues with inputouput matrix8230.Can you please help Electricity consumed internally Steel consumed internally Matrix A .25 .20 .50 .20 If the production capacity of electricity is 15 million and the production capacity for steel is 20 million how much of each is consumed internally for capacity production How much electricity and steel must be produced to have 5 million worth of electricity and 8 million worth of steel available for consumer use. Hi and thanks for writing I had to look up how to do this, but here8217s what I got: You may have also found it in the Finite Mathematics book, by Howard Rolf. Hope that helps Lisa Please help me to set up a linear system in matrix form A feeding station in a field study provides for three types of deer: young deer, adult females and adult males. There are 12 deer in all. In total, the deer consume 18.5 units of food and 14.5 units water each day. Suppose each young deer consumes 1 unit of food and 0.5 unit of water each day. The corresponding values for an adult female are 1.5 and 1, and for an adult male are 2 and 2. The ecologist needs to figure out how many young deer, adult females and adult males are in the herd. Good problem Let y young deer, f adult females, and m adult males. Then you have: Total Deer: y f m 12 Food: 1y 1.5f 2m 18.5 Water:.5y 1f 2m 14.5 Put in Matrix form and solve to get 3 young deer, 5 female deer, and 4 male deer. Could you use the inverse of the matrix to find that answer I do not know whats the purpose of using the inverse Thank you Great Question If you have the same number of variables as equations, you can get the answer to the system of equations by taking the inverse of the coefficient matrix A (the matrix with the numbers before the x, y, and z, for example) and multiplying by the constant matrix B (the matrix with the numbers on the right hand side of the equal signs). So the answer would be A-1 B, where A-1 is the inverse of A. I8217m not sure we can do that with the candy problem below since we have more variables than equations. You can look here to see how I explain it (and up a little further to see about inverses). Can we get the Rank of the matrix in the cal c Not that I know of 8211 sorry I can8217t help you here. Lisa matrices used to give me worst nightmares, it was like a ghost always giving me hard times. The day I discovered this website wow, I felt the heavy burden on my mindset disappearing, recently, I8217m in Love with matrices and I8217m good. Thanks for writing 8211 I LOVE matrices 8211 once I got them That comment made my day. Lisa one more question ask u frd 823082308230823082308230823082308230i have one question Q1. let i m taking three vehicle like car, jeep. motorcycle they are all move to 10 km. how much they will take time at each different path. i m mention below i takes three different s path like 82308230. rough. smooth. zing-zag name of vehicle smooth rough Zing-zag motorcycle 5 mint 10mt 7mt Car 6mt 7mt 9mt jeep 7mt 7mt 8mt Smooth 20 rough 50 Zing - Zag 30 which vehicle best ride for 10km 82308230.i just think and type. if u want any thing change pzl do give me ans 82308230823082308230if u have more example like cricket player. cloth. pen, room pict, home fan. etc any thing we see in normal. can we apply matrix. if we apply give me few example 823082308230823082308230.my email is krrishvishistyahoo. co. in i m waiting ur reply i hop u will back me reply soon 823082308230.. Thanks for writing. I8217m not sure I totally understand the problem, but I used matrices to multiply the type of vehicle by time on each type of road matrix (32153) by a matrix of the weights of each type of road (32151) and got a 32151 matrix of the times for each type of vehicle that is 8.1 7.4 7.3. So the jeep would have the shortest time Does this make sense thax lot for reply 82308230. 82308230823082308230. Pls can you help me solve this problem, The sum of 1200usd is invested in three projects x, y,z at the ratio of 4:5:6 respectively, the expected cash inflow per annum is 700usd, the combined income for projects x and y is 140usd more than the income from project z. calculate the amount invested in project z what is the cash inflow for project z what is the combined cash inflow for projects x and y calculate the amount invested in project y Pls don8217t write the solution in the calculator form because i don8217t have it, thanks. Thanks for writing I will try. Since the income is at a ratio of 4:5:6, we have 4x 5x 6x 1200. Solve for x and get 80. So the income for x is 421580 320, the income for y is 521580400, and the income for z is 621580480. It looks like the cash inflow for the properties are all in the same ratio (7001200), so we have the cash inflow for z (7001200)x480 280. Since the combined cash inflow for x and y is 140 more than z, their combined inflow is 420. I think that answers all the questions. Lisa thanks for quick response, help me with these also 1)A salesman has below record for products sold during peak season of october to december. The products are in three variants A B C. How many units of product C only is he expected to sell to earn 900 commission 2)The buying price of a basket of oranges is 1000 and selling price is 5 per orange. What is the profit per basket if 300 oranges are found in the basket What is the break even point(quantity),if the buying price of a basket remains 1000 and the selling price is 5 What is the profit per basket if 250 oranges are found in the basket For number 1), there is not enough information 8211 are you missing a table For 2), we have Profit Revenues 8211 Cost, so P 5(300) 8211 1000 500. For the break even quantity, 0 5x 8211 1000 x 200. For the profit if there are 250 oranges, 5(250) 8211 1000 250. Hope that makes sense. Lisa Hello Lisa, do you think you could help me with this question without a calculator A dietitian wishes to plan a meal around three foods. The meal is to include 12120 units of vitamin B, 26440 units of vitamin C, and 17260 units of Vitamin E. The number of units of the vitamins in each unit of the foods is summarised: Food I Food II Food III Vitamin B 120 300 420 Vitamin C 240 700 940 Vitamin E 160 450 610 Determine the amount of each food the dietitian should include in the meal in order to exactly meet the vitamin requirements. I tried using your section on solving systems with matrices. However, some of the values are very big and of negative values. I8217d really appreciate it if you could help me Thank you Thanks for writing I8217m getting a negative number too you may want to check with the teacher or book to make sure the numbers are correct. Here8217s a link to how it could be solved, but with different numbers: proton. ucting. udg. mxTIcalctutspc5AMCh5Chapter5StudentQuestions53studentquestions53.html If you get better numbers, let me know Thanks, Lisa Hi Lisa, Question about solving for an unknown matrix8230 When multiplying both sides of an equation by the matrix inverse, like in your problem 8220Find Q when PQ solution8221 If 8216solution8217 had also been a (22152) matrix, what would be the order of the factors Q inverse P22152 solution or Q 22152 solutioninverse P I cannot use a graphing calculator for my tests, so I really appreciate seeing all of the methods on your fabulous site Thanks Thanks for writing and thanks so much for using She Loves Math The first way you described it is correct: Q inverse P22152 solution. Try that and see if you get the correct answers (You can check by multiplying the matrices back). Hope that helps, Lisa Hi When I solve this, I get x 2 and y 1 (I used substitution). Let me know if you want any more of the work. Lisa Great Work Lisa8230..I am a Software Guy but didn8217t had the basic understanding of the Matrices, your explanation was from the basics and of great help. Now I can solve the matrices coding problems quite easily. BWT, which books would you recommend for kids between 10-15 years(for nephews)8230when i was small all books started off with 8220matrix(or any other concept) is used in large applications and should be studied seriously82218230..but never-ever did any book explain how to use it in daily basis.(the drawback of having too much knowledge by writers8230i suppose). Once again i would congratulate you for the great work. Thanks so much for taking a look at the site and writing Honestly, if you8217re just teaching the kids math topics, I always like the 82208230 for Dummies8221 books or the 8220Idiot8217s Guide to 82308221 books. They explain things really in a more direct way, and give lots of examples. Keep using my site, and please let me know if you see any ways it can be better Lisa I would like to really thank you so much for this, it really helped me revise for my maths test that is coming up this week. Keep doing this it is truly amazig () A salesman has below record for products sold during peak seson of October to December. The products are in three variants A, B amp C. How many units of product C only is he expected to sell to earn 900 commissionMonths Sales of Units A B C Total Commission drawn (N) January 90 100 20 800 200 February 130 50 40 900 300 March 60 100 30 850 400 A salesman has below record for products sold during peak seson of October to December. The products are in three variants A, B amp C. How many units of product C only is he expected to sell to earn 900 commissionMonths Sales of Units A January 90 100 20,commission800 200 BFebruary130 50 40,commission 900 300 CMarch 60 100 30,commission 850 400 Thanks for writing, but I8217m not sure I understand this problem. Are the commission numbers for October to December It looks like they are from January to March Lisa Please, I need help with solving the following problems: Problem 1: (Performance Test) A teacher estimates that of the students who pass a test 80 will pass the next test, while of the students who fail a test, 50 will pass the next test. Let x an y denote the number of students who pass and fail a given test, and let u and v be the corresponding numbers for the following test. (a) write a matrix equation relating x amp y to u amp v. (b) suppose that 25 of the teacher8217s students pass the third test and 8 fail the third test. How many students will pass the fourth test. Approximately how many passed the second test an out of shape athlete runs 6 miles per hour, swims 1 mile per hour, and bikes 10 miles per hour. He entered a triathlon, which requires all 3 events and finished it in 5 hours and 40 minutes. A friend, who runs 8 miles per hour, swims 2 miles per hour, and bikes 15 miles per hour finished the course in 3 hours and 35 minutes. The total course was 32 miles. How many miles was each segment (running, swimming and biking) New parents Jim and Lucy want to start saving for their son8221s college education. They have 5000 to invest in three different types of plans. A traditional savings account pays 3 annual interest, a certificate of deposit (CD) pays 6 annual interest, and a prepaid college plan pays 7 annual interest. If they want to invest the same amount in the prepaid college fund as in the other two plans together, how much should they invest in each plan to realize an interest income of 300 for the first year Thanks for writing. For now, I will do problem 3 let me know if you still need help on the other problems. I8217d set up like this. 03x .06y .075z 300. x y z 5000, and z x y. If I put this into a matrix and solve, I get x 1250, y 1250, and z 2500. Does that make sense Lisa Thank you so much for your help, those were the answers I got, but needed to verify. Can you please help witb question 2 which I8217m still having trouble fuguring it out. Thanks an out of shape athlete runs 6 miles per hour, swims 1 mile per hour, and bikes 10 miles per hour. He entered a triathlon, which requires all 3 events and finished it in 5 hours and 40 minutes. A friend, who runs 8 miles per hour, swims 2 miles per hour, and bikes 15 miles per hour finished the course in 3 hours and 35 minutes. The total course was 32 miles. How many miles was each segment (running, swimming and biking) Here8217s how I did this 8211 let t1, t2, t3 be times for first guy, t4, t5, t6 be times for second. t1 t2 t3 5 4060. t4 t5 t6 3 3560. Also, 6t1 t2 10t3 32, and 6t1 8t4, t2 2t5, and 10t3 15t6. Solving by matrices, I get t1 1 23, t2 2, and t3 2. So then I get the distances of 10, 2, and 20 for running, swimming and biking. Does that make sense Lisa Hello there I need some help with this word problem matrix. I8217ve been working on it for hours and have gotten absolutely nowhere A health shop owner made trail mix containing dried fruit, nuts, amp carob chips. The dried fruit sells for 5.50lb, the nuts for 7.50lb, amp 8.50lb for carob chips. The shop owner mixed 50lbs of trail mix amp sells it for 6.70lb. If the amount of nuts is 5lbs more than the carob chips, how much of each item was used in the trail mix Thanks for writing Here8217s how I8217d do this problem: 5.5f 7.5n 8.5c 50(6.7), f n c 50, n 5 c. Then I used the following matrix: 5.5 7.5 8.5 335 1 1 1 50 0 1 -1 5 (This is a 4 by 3 matrix, and I use RREF in the graphing calculator to get the answers). I get 25 lbs of fruit, 15 of nuts, and 10 of carob chips. Does this make sense Lisa OH MY GOSH, thank you so so much I was using the 6.70 for the second equation and 50lbs just for the first instead of multiplying 50 by 6.70. I appreciate it so much This website is amazing thank you for using so many examples for even upper level math courses. My Trig amp Calculus final are in a few weeks amp this will save my life for sure Aisha has RM10000 to invest. As her financial consultant, you recommend that she invest in Treasury bills that yield 6. Treasury bonds that yield 7 and corporate bonds that yield 8. Aisha wants to have an annual income of RM680, and the amount invested in corporate bond must be half that invested in Treasury bills. Find the amount of each investment. miss what the way to make this in matrixi not able to answer it and if you know to make it in c coding can u share it. Here8217s how I8217d do this: x y z 10000. 06x .07y .08z 680. z .5x. The matrix would look like 1 1 1 10000 .06 .07 .08 680 -.5 0 1 0 I get 4000 in treasury bills, 4000 in treasury bonds, and 2000 in corporate bonds. Does that make sense Lisa Hey Lisa, I really need your help A roadside fruit stand sells mangoes at Php 75 a kilo, pomelos at Php 90 a kilo, and star apples at Php 60 a kilo. Karla buys 18 kilos of fruits at a total cost of Php 1380. Her pomelos and star apple together cost Php 180 more than her mangoes. How many kilos of each kind of fruit did she buy Write a system of equations using Cramer8217s Rule. Here8217s how I8217d set up this problem: 75m 90p 60a 1380. m p a 18. 90p 60a 75m 180. We can then set up in a matrix: 75 90 60 1380 1 1 1 18 -75 90 60 180 I then get 8 mangos, 6 pomelos, and 4 star apples. You can do this with Cramer8217s Rule using the information found here. Does that make sense Lisa How much copper and how much iron should be added to 100 lb of an alloy containing 25 copper and 40 iron in order to obtain an alloy containing 30 copper and 50 iron Write a system of equations using Cramer8217s Rule. Thanks for writing I found this problem here and you can solve it using Cramer8217s Rule the way I explained here. Does that help Lisa Jane is asked to buy three sizes of bottled water: A, B and C. The total number of bottles she needs to buy is 50. She has a budget of Php 1500. Size A is Php 20 each, size B is Php 50 each, and size C is Php 30 each. Additionally, the number of bottles of size A should be equal to that size of C. How many of each size should she buy Write a system of equations using Cramer8217s Rule. Here is how I8217d set this up: a b c 50, 20a 50b 30c 1500, a c. Then you can put this in a matrix and solve using Cramer8217s Rule . Thanks, Lisa plz solve this question. show by considering minors that the matrice A inverse. A transpose inverse. have the same rank as A 8230. it will be easy for me if u attach image of the work out Thanks for writing Unfortunately, these questions are beyond the scope of this website. You might look at this site mathsisfunalgebramatrix-inverse-minors-cofactors-adjugate. html. and see if that helps So sorry 8211 I will try to do more research to see what I can figure out thought Lisa any way thanku lisa for ur help 8230 1.The buying price of a basket of oranges is 1000 and the selling price is 5 per orange. what is the profit per basket if 300 oranges are found in the basket. uma. 150 b.200 c.300 d. 500. 2. what is the break even point(quantity)if the buying price of a basket remains 1000 and the selling price is 5 Thanks for writing Here8217s how I8217d do this problem: Let x the number of oranges. Then we have Profit Revenue 8211 Cost. So Profit 5x 8211 1000. If 300 oranges are in the basket, we have Profit 5(300) 8211 1000 500 (d). The break even point would be when profit 0, so 0 5x 8211 1000, or x 200 oranges. Does that make sense Lisa Hello, I see that you have been very helpful with assisting with systems of equations and matrices. Could you please help me set this up You have been hired by a consultant for Crazy Al8217s Car Rentals in the city of Metropolis. Crazy Al8217s car rentals has a total of 2200 cars that it rents from three locations within the city: Metropolis Airport, downtown and Suburban Airport. Following is the weekly rental and return patterns: 90 of costumers who rent from Metropolis Airport return their cars to Metropolis Airport 5 rent from Metropolis Airport and return to Downtown 80 rent from Downtown and return to downtown 10 rent from Downtown and return to Metropolis Airport 10 rent from Suburban Airport and return to Metropolis Airport 5 rent from Suburban Airport and return to downtown How many of his cars should be at each of his three locations at the start of each week so that the same number of cars will be there at the end of the week (and hence at the start of the next week). Use systems of equations and matrices to set up a systems of equations representing this situation and solve this problem. Include math steps. Any help would be appreciated. I don8217t know where to even start Thanks Thanks for writing. I found this: answers. yahooquestionindexqid20140216223142AAddVGd and then it shouldn8217t be too difficult solving the system with matrices. Let me know if you want it solved. Thanks, Lisa 1) The 7th term of an A. P is 15 and the fourth term is 9. Find the common difference of the sequence 2) The 7th term of an A. P is 15 and the fourth term is 9. find the sequence fifth term. 3) The 7th term of an A. P is 15 and the fourth term is 9. Find the sequence tenth term. 4) The 7th term of an A. P is 15 and the fourth term is 9. Find the sequence first term 5) Find the 7th term of an A. P whose first term is 102 and common difference is -3, I await your respose liza. Thanks So let8217s use the equation for an arithmetic sequence: an a1 d(n 8211 1). Since 15 8211 9 is 6, and 7 8211 4 is 3, we can see that the common difference is 63 2. (See how this would mean every term goes up by 2) So we have an a1 2(n 8211 1). Let8217s plug in a 8220point8221 to get what a1 is: 15 a1 2(7 8211 1), so a1 3. So the sequence is an 3 2(n 8211 1). So the 5th term or a5 is 3 2(5 8211 1), or 11. See if you can do the other problems Thanks Lisa i need help.. question is. An automobile company uses three types of steel S1, S2 and S3.For producing three types of cars c1, c2. c3. Steel Requirements (in tons) for each type of car are given below: type of cars C1 C2 C3 S1 2 3 4 S2 1 1 2 TYPE OF STEEL S3 3 2 1 Determine the number of cars of each type which can be produced using 29, 13 and 16 tons of steel of three types respectively. Thanks for writing I put this in a matrix and got C12, C23 and C34. Here is the matrix I solved: 2 3 4 29 1 1 2 13 3 2 1 16 Does that make sense Lisa An automobile company uses three types of steel S1, S2 and S3.For producing three types of cars c1, c2. c3. Steel Requirements (in tons) for each type of car are given below: Type of car C1 C2 C3 S1 2 3 4 S2 1 1 2 S3 3 2 1 Q1. Determine the number of cars of each type which can be produced using 29, 13 and 16 tons of steel of three types respectively
Foram trinta anos desde que entrei no negócio de serviços financeiros como intermediário. Ainda me lembro do meu primeiro comércio especulativo, era um comércio de futuros que envolve Live Hogs (todos os meus amigos no negócio eram agricultores). Logo depois de entrar no negócio de finanças, eu me afastei do lado da corretora para o lado da análise, onde eu realmente queria estar. Eu devo estar fazendo algo certo, porque fui promovido para Diretor de Pesquisa na maior loja de pesquisa de opções das nações. Em 1993, deixei essa empresa para começar minha própria empresa a focar estritamente na volatilidade, e ainda tenho 21 anos depois. - Quarta-feira, 25 de julho de 2012 - O Capítulo Central da Kentucky da American Heart Association apresentou recentemente Don Fishback com o Franklin Moosnick Service Award, os capítulos locais mais honrados do voluntário. Don Fishback foi um voluntário com o capítulo do Kentucky Central por mais de 18 anos. Ele perdeu seu pai, um tio e ambos os avós pa...
Comments
Post a Comment