AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 281861
Accepted
Zoinky
Zoinky
Asked: 2020-12-20 08:30:01 +0800 CST2020-12-20 08:30:01 +0800 CST 2020-12-20 08:30:01 +0800 CST

Como adiciono Median a esta consulta?

  • 772

Eu gostaria de adicionar median à seguinte consulta, a mediana obviamente será para cada tipo de quarto, unittypeid (já no grupo por), tentei trabalhar com PERCENTILE_CONT, mas não consegui descobrir como fazê-lo funcionar.

CREATE TABLE #TempListings
(
    ListingId int,
    Price money,
    UnitTypeId int,
    BedroomsAvailable int
)
INSERT INTO #TempListings VALUES(1, 1000, 1, 1)
INSERT INTO #TempListings VALUES(2, 2000, 1, 1)
INSERT INTO #TempListings VALUES(3, 3000, 1, 1)

INSERT INTO #TempListings VALUES(4, 1000, 1, 2)
INSERT INTO #TempListings VALUES(5, 2000, 1, 2)
INSERT INTO #TempListings VALUES(6, 3000, 1, 2)

INSERT INTO #TempListings VALUES(7, 1000, 2, 1)
INSERT INTO #TempListings VALUES(8, 2000, 2, 1)
INSERT INTO #TempListings VALUES(9, 3000, 2, 1)

INSERT INTO #TempListings VALUES(10, 1000, 2, 2)
INSERT INTO #TempListings VALUES(11, 2000, 2, 2)
INSERT INTO #TempListings VALUES(12, 3000, 2, 2)
  
SELECT BedroomsAvailable, 
    COUNT(listingid) AS Count, 
    MIN(price) AS MinPrice, 
    MAX(price) AS MaxPrice, 
    AVG(price) AS AveragePrice,
    STDEV(price) as StandardDeviation,
    UnitTypeId
FROM #TempListings
GROUP BY BedroomsAvailable, UnitTypeId
ORDER BY UnitTypeId

DROP TABLE #TempListings

Estou usando o sqlserver 2019 se for importante

sql-server t-sql
  • 2 2 respostas
  • 52 Views

2 respostas

  • Voted
  1. Best Answer
    nbk
    2020-12-20T09:15:02+08:002020-12-20T09:15:02+08:00

    Você queria apenas explicar como a sintaxe funciona. Mas como consulta completa

    CREATE TABLE #TempListings
    (
        ListingId int,
        Price money,
        UnitTypeId int,
        BedroomsAvailable int
    )
    INSERT INTO #TempListings VALUES(1, 1000, 1, 1)
    INSERT INTO #TempListings VALUES(2, 2000, 1, 1)
    INSERT INTO #TempListings VALUES(3, 3000, 1, 1)
    
    INSERT INTO #TempListings VALUES(4, 1000, 1, 2)
    INSERT INTO #TempListings VALUES(5, 2000, 1, 2)
    INSERT INTO #TempListings VALUES(6, 3000, 1, 2)
    
    INSERT INTO #TempListings VALUES(7, 1000, 2, 1)
    INSERT INTO #TempListings VALUES(8, 2000, 2, 1)
    INSERT INTO #TempListings VALUES(9, 3000, 2, 1)
    
    INSERT INTO #TempListings VALUES(10, 1000, 2, 2)
    INSERT INTO #TempListings VALUES(11, 2000, 2, 2)
    INSERT INTO #TempListings VALUES(12, 3000, 2, 2)
    
    INSERT INTO #TempListings VALUES(13, 5000, 2, 1)
    INSERT INTO #TempListings VALUES(14, 6000, 2, 1)
    INSERT INTO #TempListings VALUES(15, 7000, 2, 1)
    
    INSERT INTO #TempListings VALUES(16, 8000, 2, 2)
    INSERT INTO #TempListings VALUES(17, 9000, 2, 2)
    INSERT INTO #TempListings VALUES(18, 10000, 2, 2)
    GO
    
    WITH #myselect
     AS (SELECT 
             BedroomsAvailable
             ,ListingId 
             ,UnitTypeId
             ,Price,PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Price)  
             OVER (PARTITION BY UnitTypeId) AS MedianCont
        FROM #TempListings)
    SELECT BedroomsAvailable 
        ,COUNT(listingid) AS Count 
        ,MIN(price) AS MinPrice 
        ,MAX(price) AS MaxPrice 
        ,AVG(price) AS AveragePrice
        ,STDEV(price) as StandardDeviation 
        , MIN(MedianCont) MedianCont
        ,UnitTypeId
    FROM #myselect
    GROUP BY BedroomsAvailable, UnitTypeId
    ORDER BY UnitTypeId   
    GO
    
    QuartosDisponível | Contagem | Preço mínimo | MaxPrice | Preço Médio | Desvio Padrão | MedianCont | UnitTypeId
    ----------------: | ----: | --------: | ---------: | -----------: | ----------------: | ---------: | ---------:
                    1 | 3 | 1000.0000 | 3000.0000 | 2000.0000 | 1000 | 2000 | 1
                    2 | 3 | 1000.0000 | 3000.0000 | 2000.0000 | 1000 | 2000 | 1
                    1 | 6 | 1000.0000 | 7000.0000 | 4000.0000 | 2366.43191323985 | 4000 | 2
                    2 | 6 | 1000.0000 | 10.000,0000 | 5500.0000 | 3937.00393700591 | 4000 | 2
    

    db<>fique aqui

    • 2
  2. J.D.
    2020-12-20T09:14:22+08:002020-12-20T09:14:22+08:00

    Há várias maneiras de calcular a mediana no SQL Server. Aaron Bertrand percorre os principais e compara seu desempenho em Qual é a maneira mais rápida de calcular a mediana? .

    Se você quiser usar PERCENTILE_COUNT, pode fazer desta forma:

    SELECT BedroomsAvailable, UnitTypeId, PERCENTILE_CONT(0.5) AS PriceMedian
    WITHIN GROUP (ORDER BY price) OVER (PARTITION BY BedroomsAvailable, UnitTypeId)
    FROM #TempListings
    

    Você pode então juntar isso de volta à sua consulta principal em BedroomsAvailablee UnitTypeId.

    Por exemplo:

    WITH CTE_PriceMedians AS
    (
        SELECT BedroomsAvailable, UnitTypeId, PERCENTILE_CONT(0.5) AS PriceMedian
            WITHIN GROUP (ORDER BY price) OVER (PARTITION BY BedroomsAvailable, UnitTypeId)
        FROM #TempListings
    )
    
    SELECT BedroomsAvailable 
        ,COUNT(listingid) AS Count 
        ,MIN(price) AS MinPrice 
        ,MAX(price) AS MaxPrice 
        ,AVG(price) AS AveragePrice
        ,STDEV(price) as StandardDeviation 
        ,MIN(MedianCont) MedianCont
        ,UnitTypeId
        ,PriceMedian
        ,SUM(price)/COUNT(1) AS PriceMean
    FROM #TempListings AS TL
    INNER JOIN CTE_PriceMedians AS PM
        ON TL.BedroomsAvailable = PM.BedroomsAvailable
        AND TL.UnitTypeId = PM.UnitTypeId
    GROUP BY BedroomsAvailable, UnitTypeId
    ORDER BY UnitTypeId   
    
    • 1

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve