Pivot with Temporary Table

Asked

Viewed 79 times

0

Hello. I am building a query where I need to use pivot to analyze the results, but it does not return the necessary data.

Original table:

    select * from tbCampoAdicionalTicket where TCK_SEQUENCIAL = 415945

Resultado

I need the CAT_VALOR column to become a single row. However, I find some problems when creating the pivot:

1 - The column TCK_SEQUENCIAL exists through a foreign key, and I cannot call it in the pivot select.

2 - The CAT_VALOR column is of the VARCHAR type and I cannot convert it because there are cases with text.

Below, the closest I could create from the pivot, but the result returns a table with all NULL values:


SELECT  TCK_SEQUENCIAL, 
        [1] AS CAT_NUMERO_1, 
        [2] AS CAT_NUMERO_2, 
        [3] AS CAT_NUMERO_3, 
        [4] AS CAT_NUMERO_4 
FROM tbCampoAdicionalTicket
PIVOT(
    MAX(CAT_VALOR)
    FOR CAT_NUMERO IN (
    [1],
    [2],
    [3],
    [4])) AS pivot_table
WHERE TCK_SEQUENCIAL = 415948 

I would like the result to be similar to the photo, but with the column TCK_SEQUENCIAL together, because this table will be used in a previous:

resultado

From now on I thank you all!

  • Hello alive puts a table with the expected result, to be clearer.

  • You have here some examples of PIVOT, check if help.

  • Ernesto, follow a better example image. The first image is my original table, the second is the pivot, but I need to group it in a single line

  • Which SGDB this using?

2 answers

0

I was able to solve the problem through the following script:

    SELECT DISTINCT MAX(pivot_table.TCK_SEQUENCIAL) AS TCK_SEQUENCIAL, 
                    MAX([1])                        AS CAT_NUMERO_1, 
                    MAX([2])                        AS CAT_NUMERO_2, 
                    MAX([3])                        AS CAT_NUMERO_3, 
                    MAX([4])                        AS CAT_NUMERO_4,

    FROM tbCampoAdicionalTicket CAT
                    PIVOT(MAX(CAT_VALOR) FOR CAT_NUMERO IN (
                    [1], [2], [3], [4], [5], [6], [7], [8], [9], [10])) AS pivot_table
  • Your solution, it works, yet it will have a higher execution weight than my solution. The database not having many records is not critical if it has rethink or revises your query. Check the Execution plan of the two queries in management studio with CRTL + L.

0


Hello you have here the solution,

SELECT  TCK_SEQUENCIAL, [1] AS CAT_NUMERO_1, 
        [2] AS CAT_NUMERO_2, 
        [3] AS CAT_NUMERO_3, 
        [4] AS CAT_NUMERO_4
FROM
(
    SELECT TCK_SEQUENCIAL, CAT_NUMERO, CAT_VALOR
    FROM tbCampoAdicionalTicket
) x
PIVOT(
    MAX(CAT_VALOR)
    FOR CAT_NUMERO IN (
    [1],
    [2],
    [3],
    [4])) AS pivot_table
WHERE TCK_SEQUENCIAL = 415948 
  • I managed with a slight modification in your remark.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.