I have a 3 datbles Dealer, payment_type and dealer_payment_type
Dealer : dealer_id , dealer_name, dealer_address
1 | test | 123 test lane
2 | abc | abc lane
3 | def | def lane
Payment_type : paymenttype_id , paytype
1 | CHECK
2 | WIRE
3 | CREDIT
Dealer_Payment_type : DPT_id , dealer_id , payment_type_id
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 2 | 2
5 | 2 | 3
6 | 3 | 1
7 | 3 | 2
I have to write a query to get payment type info for each dealer , query needs to return data like this:
dealer_id , dealer_name , paytype
1 | test | check,wire,credit
2 | abc | wire,credit
3 | def | check,wire
OR
dealer_id , dealer_name , check , wire , credit
1 | test | true | true | true
2 | abc | false | true | true
3 | def | true | false | true
You did not specify what version of Oracle you are using.
If you are using Oracle 11g, then you can use the following.
To get the values into a single column, then you can use LISTAGG:
select d.dealer_id,
d.dealer_name,
listagg(p.paytype, ',') within group (order by d.dealer_id) as paytype
from dealer d
left join Dealer_Payment_type dp
on d.dealer_id = dp.dealer_id
left join payment_type p
on dp.payment_type_id = p.paymenttype_id
group by d.dealer_id, d.dealer_name;
See SQL Fiddle with demo
To get the values in separate columns, then you can use PIVOT:
select dealer_id, dealer_name,
coalesce("Check", 'false') "Check",
coalesce("Wire", 'false') "Wire",
coalesce("Credit", 'false') "Credit"
from
(
select d.dealer_id,
d.dealer_name,
p.paytype,
'true' flag
from dealer d
left join Dealer_Payment_type dp
on d.dealer_id = dp.dealer_id
left join payment_type p
on dp.payment_type_id = p.paymenttype_id
)
pivot
(
max(flag)
for paytype in ('CHECK' as "Check", 'WIRE' as "Wire", 'CREDIT' as "Credit")
)
See SQL Fiddle with Demo.
If you are not using Oracle 11g, then you can use wm_concat() to concatenate the values into a single row:
select d.dealer_id,
d.dealer_name,
wm_concat(p.paytype) as paytype
from dealer d
left join Dealer_Payment_type dp
on d.dealer_id = dp.dealer_id
left join payment_type p
on dp.payment_type_id = p.paymenttype_id
group by d.dealer_id, d.dealer_name;
To create the separate columns, then you can use an aggregate function with a CASE:
select dealer_id, dealer_name,
max(case when paytype = 'CHECK' then flag else 'false' end) "Check",
max(case when paytype = 'WIRE' then flag else 'false' end) "Wire",
max(case when paytype = 'CREDIT' then flag else 'false' end) "Credit"
from
(
select d.dealer_id,
d.dealer_name,
p.paytype,
'true' flag
from dealer d
left join Dealer_Payment_type dp
on d.dealer_id = dp.dealer_id
left join payment_type p
on dp.payment_type_id = p.paymenttype_id
)
group by dealer_id, dealer_name;
See SQL Fiddle with Demo
Related
I have 3 tables in SQL Server 2012.
Table History is the history of all the changes made to the values in Table A. It can have many changes done to PRICE, LOT, INTEREST, but in most cases the value is only changed once.
Table A
AID PRICE LOT INTEREST
------------------------
1 1500 10 0.5
2 2500 20 1.5
Table B
BID AID
--------
11 1
22 2
Table History.
BID ChangeField OldValue NewValue ChangeDate
------------------------------------------------------------
11 PRICE 1700 1500 1/1/22
11 LOT 15 10 12/15/21
11 update_flag M 1/1/22
I need a query that shows Table A with the old and new values from Table History. If there are more than 1 changes, then for the Old value, get the most recent previous value.
Example:
AID OldPRICE NewPRICE OldLot NewLot OldInterest NewInterest
----------------------------------------------------------------
1 1700 1500 15 10 0.5 0.5
2 2500 2500 20 20 1.5 1.5
How can I do that ?
Thank you.
First you need to join all three tables and aggregate per AID. Once you have that, the query needs to selectively pick the values from the history should they exist.
For example:
select
a.aid,
max(case when h.changefield = 'PRICE' then coalesce(h.oldvalue, a.price) end) as oldprice,
max(case when h.changefield = 'PRICE' then coalesce(h.newvalue, a.price) end) as newprice,
max(case when h.changefield = 'LOT' then coalesce(h.oldvalue, a.lot) end) as oldlot,
max(case when h.changefield = 'LOT' then coalesce(h.newvalue, a.lot) end) as newlot,
max(case when h.changefield = 'INTEREST' then coalesce(h.oldvalue, a.interest) end) as oldinterest,
max(case when h.changefield = 'INTEREST' then coalesce(h.newvalue, a.interest) end) as newinterest
from table_a a
left join table_b b on b.aid = a.aid
left join history h on h.bid = b.bid
group by a.aid
You can try to use OUTER JOIN with the condition aggregate function.
Query 1:
SELECT A.AID,
MAX(ISNULL(CASE WHEN h.ChangeField = 'PRICE' THEN h.OldValue END,A.PRICE)) OldPRICE,
MAX(ISNULL(CASE WHEN h.ChangeField = 'PRICE' THEN h.NewValue END,A.PRICE)) NewPRICE,
MAX(ISNULL(CASE WHEN h.ChangeField = 'LOT' THEN h.OldValue END,A.LOT)) OldLot,
MAX(ISNULL(CASE WHEN h.ChangeField = 'LOT' THEN h.NewValue END,A.LOT)) NewLot,
MAX(ISNULL(CASE WHEN h.ChangeField = 'INTEREST' THEN h.OldValue END,A.INTEREST)) OldInterest,
MAX(ISNULL(CASE WHEN h.ChangeField = 'INTEREST' THEN h.NewValue END,A.INTEREST)) NewInterest
FROM A
LEFT JOIN B ON A.AID = B.AID
LEFT JOIN History h ON B.BID = h.BID
GROUP BY A.AID
Results:
| AID | OldPRICE | NewPRICE | OldLot | NewLot | OldInterest | NewInterest |
|-----|----------|----------|--------|--------|-------------|-------------|
| 1 | 1700 | 1500 | 15 | 10 | 0.5 | 0.5 |
| 2 | 2500 | 2500 | 20 | 20 | 1.5 | 1.5 |
I have these tables and values:
Person Account
------------------ -----------------------
ID | CREATED_BY ID | TYPE | DATA
------------------ -----------------------
1 | 1 | T1 | USEFUL DATA
2 | 2 | T2 |
3 | 3 | T3 |
4 | 4 | T2 |
Person_account_link
--------------------------
ID | PERSON_ID | ACCOUNT_ID
--------------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3
4 | 3 | 4
I want to select all persons with T1 account type and get the data column, for the others persons they should be in the result without any account information.
(I note that person 1 has two accounts : account_id_1 and account_id_2 but only one row must be displayed (priority for T1 type if exist otherwise null)
The result should be :
Table1
-----------------------------------------------------
PERSON_ID | ACCOUNT_ID | ACCOUNT_TYPE | ACCOUNT_DATA
-----------------------------------------------------
1 | 1 | T1 | USEFUL DATA
2 | NULL | NULL | NULL
3 | NULL | NULL | NULL
4 | NULL | NULL | NULL
You can do conditional aggregation :
SELECT p.id,
MAX(CASE WHEN a.type = 'T1' THEN a.id END) AS ACCOUNT_ID,
MAX(CASE WHEN a.type = 'T1' THEN 'T1' END) AS ACCOUNT_TYPE,
MAX(CASE WHEN a.type = 'T1' THEN a.data END) AS ACCOUNT_DATA
FROM person p LEFT JOIN
Person_account_link pl
ON p.id = pl.person_id LEFT JOIN
account a
ON pl.account_id = a.id
GROUP BY p.id;
You would need an outer join, starting with Person and then to the other two tables. I would also aggregate with group by and min to tackle the situation where a person would have two or more T1 accounts. In that case one of the data is taken (the min of them):
select p.id person_id,
min(a.id) account_id,
min(a.type) account_type,
min(a.data) account_data
from Person p
left join Person_account_link pa on p.id = pa.person_id
left join Account a on pa.account_id = a.id and a.type = 'T1'
group by p.id
In Postgres, I like to use the FILTER keyword. In addition, the Person table is not needed if you only want persons with an account. If you want all persons:
SELECT p.id,
MAX(a.id) FILTER (a.type = 'T1') as account_id,
MAX(a.type) FILTER (a.type = 'T1') as account_type,
MAX(a.data) FILTER (a.type = 'T1') as account_data
FROM Person p LEFT JOIN
Person_account_link pl
ON pl.person_id = p.id LEFT JOIN
account a
ON pl.account_id = a.id
GROUP BY p.id;
I have below data and it will have multiple titles against multiple genres. Every genre has 7 top titles.
Genre | MarketingTitle
------+----------------
Drama | Drama 1
Drama | Drama 2
...
Drama | Drama 7
I want output to look something like
Genre | Title 1 | Title 2 | Title 3 | ... | Title7
-------+---------+---------+---------+-----+---------
Drama | Drama1 | Drama2 | Drama3 | ... | Drama7
Comedy | Comedy1 | Comedy2 | Comedy3 | ... | Comedy7
I tried pivot table but its just not working
Select
GenreName, [Drama], [Comedy]
from
(select
g.name as GenreName, p.MarketingTitle as MarketingTitle
from
programme p
inner join
Genre g on g.Id = p.GenreId
where
topTitle = 1) c
pivot
(max(MarketingTitle)
for MarketingTitle in ([Drama], [Comedy])
) As pvt
Everything is returned as null and I am pretty sure this query is wrong.
Even below output is desirable but I cant seem to make query work. any help is appreciated.
Drama | Comedy | ... | otherGenres
--------+---------+-----+------------
drama1 | comedy1 | ... |
drama2 | comedy2 | ... |
.. .
drama7 | comedy7 | ... |
Try conditional aggregation instead
select
GenreName, Title1 = max(case when rn = 1 then MarketingTitle end)
, Title2 = max(case when rn = 2 then MarketingTitle end)
, Title3 = max(case when rn = 3 then MarketingTitle end)
, Title4 = max(case when rn = 4 then MarketingTitle end)
, Title5 = max(case when rn = 5 then MarketingTitle end)
, Title6 = max(case when rn = 6 then MarketingTitle end)
, Title7 = max(case when rn = 7 then MarketingTitle end)
from (
select g.name as GenreName, p.MarketingTitle as MarketingTitle
, rn = row_number() over (partition by g.name order by p.MarketingTitle)
from programme p
inner join Genre g on g.Id = p.GenreId
where top = 1
) t
group by GenreName
I have the following SQL statement. It joins three tables: Person, Deliverable, and DeliverableActions
select
p.first_name, p. last_name, d.title, da.type
from
Deliverable d
right join
Person p on d.person_responsible_id = p.id
right join
DeliverableAction da on da.DeliverableID = d.id
where
d.date_deadline >= #startDate and
d.date_deadline <= #endDate
order by
d.title
The result is the following:
first_name | last_name | title | type
-----------+-------------+--------------+------
Joe | Kewl | My_Report_1 | 2
Joe | Kewl | My_Report_1 | 3
Joe | Kewl | My_Report_1 | 1
Sly | Foxx | Other_Rep_1 | 1
Sly | Foxx | Other_Rep_1 | 2
My goal result is to get the following table:
first_name | last_name | title | type_1 | type_2 | type_3 | type_4
-----------+------------+--------------+--------+--------+--------+---------
Joe | Kewl | My_report_1 | 1 | 1 | 1 | 0
Sly | Foxx | Other_Rep_1 | 1 | 1 | 0 | 0
Unfortunately I don't know what term to describe what I'm doing. I've searched 'grouping' and 'aggregation', but I'm left without an answer so I am putting it to the community. Thank you in advance for your help.
you can use case based aggregation or you can also use pivot
select p.first_name,
p. last_name,
d.title,
sum(case when da.type = 1 then 1 else 0 end) as type_1,
sum(case when da.type = 2 then 1 else 0 end) as type_2,
sum(case when da.type = 3 then 1 else 0 end) as type_3,
sum(case when da.type = 4 then 1 else 0 end) as type_4,
from Deliverable d
right join Person p on d.person_responsible_id = p.id
right join DeliverableAction da on da.DeliverableID = d.id
where d.date_deadline >= #startDate and
d.date_deadline <= #endDate
group by p.first_name, p.last_name, d.title
select
first_name, last_name, title,
sum(case when type = 1 then 1 else 0 end) as type_1
from
(
select p.first_name, p. last_name, d.title, da.type from Deliverable d
right join Person p on d.person_responsible_id = p.id
right join DeliverableAction da on da.DeliverableID = d.id
where d.date_deadline >= #startDate and
d.date_deadline <= #endDate
) as a
group by first_name, last_name, title
You're looking for PIVOT
If you're using SQL Server 2008+, it has pivot function as described at http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
Basically, you write something like (sorry, I just pasted example from the quoted link but that should give you some idea):
-- Pivot table with one row and five columns
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days,
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost
FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;
First I will explain the case, I have a table tbl_game with a structure as such. This table contains, the time where the game was started and pair playing the game
| id | time | pair_id |
-----------+--------------+ ---------------
1 | 123123123 | 1 |
2 | 123168877 | 1 |
and I have another table tbl_throws which holds the score for each player. In case you are wondering, this a basic dice rolling game
| id | game_id | player_id | score |
-----------+--------------+---------------+---------|
| 1 | 1 | 1 | 2 |
| 2 | 1 | 2 | 5 |
| 3 | 1 | 1 | 9 |
| 4 | 1 | 2 | 11 |
| 5 | 2 | 1 | 7 |
| 6 | 2 | 2 | 6 |
Now, id here is the throw id, not the game id. Here each player with player_id 1 and 2 has throws the dice twice and got the respective score as presented all in same game and just one time in another
Now, using these two table, I need to create a record set, that the total score of each player in one game
| game_id | game_time | player1_total | player2_total|
|------------+-----------+---------------+--------------|
| 1 | 123123123 | 11 | 16 |
| 2 | 123168877 | 7 | 6 |
I tried lots of mumbo jumbo queries, but nothing is giving corrent result?
What is the correct query for this?
Update
Since, most of the answers were bounded by a fact that, player1id and player2id had to be known or fixed.
So may be the information I am about to provide will help to clear the confusion.
there is another table, which holds the information of the player. tbl_pupil
Structure is like the following
| id | unique_id | name |
|---------+---------------+----------|
| 1 | 001 | some |
| 2 | 002 | another |
and these player are collectively called, a pair in another table tbl_pair
| id | player1 | player2 |
|---------+---------------+----------|
| 1 | 1 | 2 |
So, now
select
g.id
g.time
p1.id as player1id
p1.name as player1name
t.score as player1score
p2.id as player2id
p2.name as player2name
t.score as player2score
FROM
tbl_game g,
inner join tbl_pair as pair on g.pair_id = pair.id
inner join tbl_pupil as p1 on p1.id = pair.player1
inner join tbl_pupil as p2 on p2.id = pair.player2
inner join tbl_throw as t on g.id = t.game_id
This is my preliminary query, which brings the record set, on a way as such
| id | time | player1id | player1name | player1score | player2id | player2name | player2score |
----------------------------------------------------------------------------------------------------------------------------
| 1 | 12 | 1 | some | 5 | 2 | another | 2 |
| 1 | 12 | 1 | some | 5 | 2 | another | 5 |
| 1 | 12 | 1 | some | 9 | 2 | another | 9 |
| 1 | 12 | 1 | some | 11 | 2 | another | 11 |
Now I am just showing the results of one game id by the way. I don't save sufficient knowledge, to group the above record into one, with player1 separate sum score in one column and playe2's separate sum of score in another column.
Try this:
SELECT
tbl_game.id AS game_id,
tbl_game.time AS game_time,
SUM(CASE WHEN player_id = 1 THEN score ELSE 0 END) AS player1_total,
SUM(CASE WHEN player_id = 2 THEN score ELSE 0 END) AS player2_total
FROM tbl_game JOIN tbl_thorws ON tbl_game.id = tbl_throws.game_id
GROUP BY tbl_game.id
This is similar to some of the other answers, but crucially doesn't depend on the player IDs being 1 and 2.
select
game_id = g.id,
game_time = g.time,
player1_total = SUM(case t.player_id when p.player1_id then t.score else 0 end),
player2_total = SUM(case t.player_id when p.player2_id then t.score else 0 end)
from
tbl_game g
join tbl_throws t on g.id = t.game_id
join ( --Get the player IDs for this game
select
game_id,
player1_id = MIN(player_id),
player2_id = MAX(player_id)
from
tbl_throws
group by game_id
) p
on p.game_id = t.game_id
group by
g.id, g.time
Just for fun I've generalized the above out to allow more > 2 players:
The 2 CTE tables just show the test data I'm using
;WITH tbl_game as (
select ID = 1, time = 123123123, pair_id = 1
union select ID = 2, time = 123168877, pair_id = 1
),
tbl_throws as (
select id = 1, game_id = 1, player_id = 1, score = 2
union select id = 2, game_id = 1, player_id = 2, score = 5
union select id = 2, game_id = 1, player_id = 3, score = 5
union select id = 3, game_id = 1, player_id = 1, score = 9
union select id = 4, game_id = 1, player_id = 2, score = 11
union select id = 5, game_id = 2, player_id = 1, score = 7
union select id = 6, game_id = 2, player_id = 2, score = 6
)
select
game_id = g.id,
game_time = g.time,
player1_id = MAX(case x.player_no when 1 then t.player_id else 0 end),
player1_total = SUM(case x.player_no when 1 then t.score else 0 end),
player1_id = MAX(case x.player_no when 2 then t.player_id else 0 end),
player2_total = SUM(case x.player_no when 2 then t.score else 0 end),
player3_id = MAX(case x.player_no when 3 then t.player_id else 0 end),
player3_total = SUM(case x.player_no when 3 then t.score else 0 end),
player4_id = MAX(case x.player_no when 4 then t.player_id else 0 end),
player4_total = SUM(case x.player_no when 4 then t.score else 0 end)
/* Add more rows for the number of players permitted in a single game */
from
tbl_game g
join tbl_throws t on g.id = t.game_id
cross apply (
select player_no = COUNT(distinct player_id)
from tbl_throws sub
where sub.player_id <= t.player_id
and Sub.game_id = t.game_id
) x
group by
g.id, g.time
You need to inner join the two tables, and aggregate your scores. To do the basic pivot you are after I used a CASE statement to aggregate by player.
SELECT G.Id as Game_Id,
G.time as Game_Time,
SUM(CASE WHEN t.Player_id = 1 THEN t.score ELSE 0 END) as Player1_total,
SUM(CASE WHEN t.Player_id = 2 THEN t.score ELSE 0 END) as Player2_total
FROM tbl_game G
INNER JOIN tbl_throws T
ON g.id = t.game_id
GROUP BY g.ID, g.time
I think this should do pretty much what you want to do.
SELECT
tbl_game.id as game_id,
tbl_game.time as game_time,
SUM(player1.score) as player1_total,
SUM(player2.score) as player2_total
FROM tbl_game
INNER JOIN tbl_throws player1 ON player1.game_id = tbl_game.id AND player1.player_id = 1
INNER JOIN tbl_throws player2 ON player2.game_id = tbl_game.id AND player2.player_id = 2
GROUP BY tbl_game.id, tbl_game.time
SELECT t.game_id
, t.game_time
, ( SELECT SUM(t.score)
FROM tbl_throws AS t
WHERE t.game_id = g.id
AND player_id = 1
) AS player1_total
, ( SELECT SUM(t.score)
FROM tbl_throws AS t
WHERE t.game_id = g.id
AND player_id = 2
) AS player2_total
FROM tbl_game AS g