Home >Database >Mysql Tutorial >How to Avoid Data Loss When Using PIVOT Queries on Distinct Records with Zero Values?

How to Avoid Data Loss When Using PIVOT Queries on Distinct Records with Zero Values?

DDD
DDDOriginal
2025-01-05 20:20:411004browse

How to Avoid Data Loss When Using PIVOT Queries on Distinct Records with Zero Values?

Avoiding Data Loss in PIVOT Queries for Distinct Records

Problem:
PIVOT queries are useful for restructuring data to display information in a more organized manner. However, when dealing with distinct records, the MAX aggregation function can cause zero values to be omitted, leading to incomplete data.

Solution:
To preserve all distinct records, even those with zero values, one can incorporate the ROW_NUMBER() function into the PIVOT query. This approach assigns a row number to each record, maintaining the association between activities and percentages.

;with cte as 
(
    select *, ROW_NUMBER() over (partition by name order by percentage desc) ROWNUM
    from A
),
cte2 as
(
    SELECT Id,Code,ROWNUM,James,James_,Sam,Sam_,Lisa,Lisa_
    FROM cte
    PIVOT(MAX(activity)
          FOR name IN (James,Sam,Lisa)) AS PVTTable PIVOT
          (
          MAX(percentage)
          FOR name1 IN (James_,Sam_,Lisa_)) AS PVTTable1
)
select Id, Code, MAX(James) James, MAX(James_) James_, MAX(Sam) Sam, MAX(Sam_) Sam_, MAX(Lisa) Lisa, MAX(Lisa_) Lisa_
from cte2
group by Id, Code, ROWNUM

Example:

Consider the following table:

Id Code percentage name name1 activity
1 Prashant 43.43 James James_ Running
1 Prashant 70.43 Sam Sam_ Cooking
1 Prashant 90.34 Lisa Lisa_ Walking
1 Prashant 0.00 James James_ Stealing
1 Prashant 0.00 James James_ Lacking
1 Prashant 73 Sam Sam_ Cooking 1

Previously, a standard PIVOT query would have produced the following result:

Id Code James James_ Sam Sam_ Lisa Lisa_
1 Prashant Running 43.43 Cooking 1 73 Walking 90.34
1 Prashant Stealing 0.0 Cooking 3.43 NULL NULL
1 Prashant NULL NULL NULL NULL NULL NULL

However, by incorporating the ROW_NUMBER() function, the modified query retains all distinct records:

Id Code James James_ Sam Sam_ Lisa Lisa_
1 Prashant Running 43.43 Cooking 1 73 Walking 90.34
1 Prashant Stealing 0.00 Cooking 3.43 NULL NULL
1 Prashant Lacking 0.00 NULL NULL NULL NULL

This approach ensures that all distinct activities are displayed, even those with zero percentage values, providing a more accurate representation of the data.

The above is the detailed content of How to Avoid Data Loss When Using PIVOT Queries on Distinct Records with Zero Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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