Skip to content
Advertisement

Join on existing aggregate query to pivot result without id

On a Sql-Server instance, I have three tables:

ActionItem

Id Name
1 Fish
2 Gravy
3 Pants

ActionData

Id ActionId Group Field Value
1 1 1 1 100
2 1 1 2 200
3 1 1 3 300
4 1 1 4 NULL
5 1 1 5 NULL
6 1 2 6 “Some Text”
7 2 1 1 50
8 2 1 2 60
9 2 1 3 70

Costing

Id ActionId Break Cost
1 1 Normal 11.3
2 1 Sub 54
3 1 Premium 0.4
4 3 Normal 22
5 3 Premium 0.67

I have a query that sums the cost for each ActionItem:

Nice and straight-forward:

Id Name (No column name)
1 Fish 65.7
2 Gravy NULL
3 Pants 22.67

I created a pivot too:

Which gets me data in the right format:

Group Field 1 2 3 4
1 1 100 50 NULL NULL
1 2 200 60 NULL NULL
1 3 300 70 NULL NULL
1 4 NULL NULL NULL NULL
1 5 NULL NULL NULL NULL
2 6 “Some Text” NULL NULL NULL

But I cannot join these two queries together because that PIVOT doesn’t contain the ActionId … even though I use Select * from – how can I get the ActionId col to show on my pivoted data, so I can join it to the rest of my original query?

I could not get sqlfiddle.com to work for MS SQL SERVER today but here are create and inserts if anyone’s interested:

Advertisement

Answer

Not sure what output you expect.
But here’s an attempt to join the two queries in 1 pivot.

ActionId | Name  |    1 |    2 |    3 |    4 | Normal | Premium |  Sub
-------: | :---- | ---: | ---: | ---: | ---: | -----: | ------: | ---:
       1 | Fish  |  100 |  200 |  300 | null |   11.3 |     0.4 |   54
       2 | Gravy |   50 |   60 |   70 | null |   null |    null | null
       3 | Pants | null | null | null | null |     22 |    0.67 | null

db<>fiddle here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement