Home > Database > Mysql Tutorial > How to Pivot Product Metadata in SQL Server 2000 using a JOIN and Aggregate Function?

How to Pivot Product Metadata in SQL Server 2000 using a JOIN and Aggregate Function?

Patricia Arquette
Release: 2025-01-02 18:29:39
Original
401 people have browsed it

How to Pivot Product Metadata in SQL Server 2000 using a JOIN and Aggregate Function?

Pivot Transformation using SQL Server 2000

Problem:

Your database contains two tables, Products and Product Meta, with the following structures:

Products:
- ProductId
- Name

Product Meta:
- ProductId
- MetaKey
- MetaValue
Copy after login

You wish to transform this data into a result set that pivots the MetaValue column, based on the MetaKey column. The desired result set is:

ProductId | Name | A | B | C
Copy after login

Solution:

Although the previously suggested solutions may not be optimal, they nonetheless highlight the use of aggregate functions or subqueries to ensure valid grouping. Here's an alternative approach:

SELECT
  P.ProductId,
  P.Name,
  MAX(CASE WHEN PM.MetaKey = 'A' THEN PM.MetaValue END) AS A,
  MAX(CASE WHEN PM.MetaKey = 'B' THEN PM.MetaValue END) AS B,
  MAX(CASE WHEN PM.MetaKey = 'C' THEN PM.MetaValue END) AS C
FROM Products AS P
LEFT JOIN ProductMeta AS PM
  ON PM.ProductId = P.ProductId
GROUP BY
  P.ProductId,
  P.Name;
Copy after login

This query joins the Products and Product Meta tables, grouping the results by ProductId and Name. The aggregate function MAX() is used to extract the maximum MetaValue for each MetaKey. This ensures that only the latest or most recent MetaValue for each key is included in the result set.

The above is the detailed content of How to Pivot Product Metadata in SQL Server 2000 using a JOIN and Aggregate Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template