Domanda

Ho una query selezionata che attualmente produce i seguenti risultati:

Description   Code    Price
 Product 1     A        5
 Product 1     B        4
 Product 1     C        2

Utilizzando la seguente query:

SELECT DISTINCT np.Description, p.promotionalCode, p.Price
FROM            Price AS p INNER JOIN
                         nProduct AS np ON p.nProduct = np.Id

Voglio produrre quanto segue:

Description  A  B  C
 Product 1   5  4  2
È stato utile?

Soluzione

SELECT 
    np.Id, 
    np.Description, 
    MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',
    MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',
    MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'
FROM 
    Price AS p 
INNER JOIN nProduct AS np ON p.nProduct = np.Id
GROUP BY 
    np.Id,
    np.Description

Ecco un semplice esempio di test:

DECLARE @temp TABLE (
    id INT,
    description varchar(50),
    promotionalCode char(1),
    Price smallmoney
)

INSERT INTO @temp
select 1, 'Product 1', 'A', 5
    union
SELECT 1, 'Product 1',  'B', 4
    union
SELECT 1, 'Product 1', 'C', 2



SELECT
    id,
    description,
    MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',
    MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',
    MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'
FROM
     @temp
GROUP BY 
    id,
    description

Altri suggerimenti

Se si utilizza SQL Server 2005, è possibile utilizzare il nuovo operatore PIVOT.

PIVOT semplice: il numero di ordini che un cliente effettua per singoli prodotti.

Struttura di una semplice tabella degli ordini:

CREATE TABLE Sales.[Order]
    (Customer varchar(8), Product varchar(5), Quantity int)

La tabella contiene i seguenti valori:

Customer Product Quantity
    Mike     Bike    3
    Mike     Chain   2
    Mike     Bike    5
    Lisa     Bike    3
    Lisa     Chain   3
    Lisa     Chain   4

Es .: un'operazione PIVOT nella tabella degli ordini:

SELECT *
    FROM Sales.[Order]
    PIVOT (SUM(Quantity) FOR Product IN ([Bike],[Chain])) AS PVT

L'output previsto da questa query è:

Customer Bike Chain
Lisa        3    7
Mike        8    2

Se non si utilizza SQL Server, è possibile cercare " pivot " per il tuo database.

La risposta di Duckworth è buona. Se è possibile ottenere più di un valore per ogni cella, è possibile utilizzare AVG o SUM anziché MIN, a seconda di ciò che si desidera visualizzare.

Se il tuo DBMS lo supporta, potresti anche voler esaminare una query a campi incrociati o una query pivot. Ad esempio, MS Access ha query a campi incrociati.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top