SQL get latest record for each ID - sql

I have three tables that contains data as below:
Users
Id Name Other_Columns
---------------------------
1 John Blah
2 Ricky Blah
3 Stella Blah
4 Bob Blah
Saldo
Id User_id Saldo
--------------------
1 3 0.00
2 1 9.00
3 2 0.15
4 4 3.50
Payments
Id User_id Amount Paid_date
------------------------------------------
1 2 10.00 2014-09-01 08:10
2 2 25.00 2014-09-01 09:00
3 3 100.00 2014-05-10 12:47
4 1 20.50 2014-02-23 15:30
How to get result like this:
Id Name Saldo Last Payment
------------------------------------------
1 John 9.00 23.02.2014 20.50
2 Ricky 0.15 01.09.2014 25.00
3 Stella 0.00 0000-00-00 0.00
4 Bob 3.50 10.05.2014 100.00
Thank you.

select u.id, u.name, s.saldo, p.last_paid_date, p2.amount
from users u
join saldo s
on u.id = s.user_id
join (select user_id, max(paid_date) as last_paid_date
from payments
group by user_id) p
on u.id = p.user_id
join payments p2
on p.last_paid_date = p2.paid_date
and p.user_id = p2.user_id
This answer assumes:
(1) On table SALDO, there is one row per USER_ID
(2) On table PAYMENTS, there can be multiple rows per USER_ID
(I'm pretty confident about #2 being true, I don't know about #1, as you didn't say and your sample data doesn't indicate one way or the other)

Related

How can I create a multi table in sql?

I have two tables. In one there is a column with the price of the product and I need to combine it with the column nazwa_kategorii in the second, and write out the sum of all services.
Nazwa usługi Cena usługi ID Kategorii
Abonament za Internet 40.00 1
Bezpieczny Internet 9.90 3
Telewizja Pakiet pełny 80.00 2
GigaNagrywarka 15.00 2
Rabat za Internet -20.00 1
ID Kategorii Nazwa Kategorii Kolejność sortowania
1 Internet 1
2 Telewizja 3
3 Usługi Dodatkowe 2
At the end it should give this result:
Kategoria podsumowania Kwota
Internet 20.00
Usługi Dodatkowe 9.90
Telewizja 95.00
I can't figure out how to complete the query so that it writes me all the columns, not just one. Here is an example:
select Nazwa_kategorii,sum(Cena_uslugi ) as kwota
from (Kategorii left join Uslugi on Kategorii.id_kategorii = Uslugi.id_kategorii)
where (Uslugi.id_kategorii =1 );
Try this:
select nazwa_kategorii, sum(cena_uslugi) kwota
from kategorie k
join uslugi u on k.id_kat = u.id_kat
group by nazwa_kategorii
nazwa_kategorii
kwota
Telewizja
95.00
Usługi dodatkowe
9.90
Internet
20.00
https://dbfiddle.uk/?rdbms=postgres_14&fiddle=35d64442a58ed811cbbffddcf60245f2

Query with sum functions

for a little project(hobby purpose) i am building a C# application with a SQL database behind it.
However I am trying to build a query with a sum function which calculates values from a different table.
Here are the relevant tables and sample data
Hotel table
Id, Name Adress Zipcode Phone
1 Ankunding Group 90 Shelley Terrace 649-6326 86-(672)239-5855
2 Gerlach-Gutmann 50776 Bartillon Road 27109 CEDEX 33-(412)226-8055
3 Breitenberg-Smith 3289 Talisman Avenue 59762 86-(141)636-8780
4 Smitham-Marks 5 Veith Plaza 216282 7-(400)484-7233
5 Beatty LLC 3 Center Pass 940028 212-(310)974-4364
Reservation table
id, customerid, Startdate Enddate Amount of persons
1 163 2016-06-19 2017-04-30 4
2 172 2016-12-02 2016-08-18 5
3 162 2017-01-20 2017-04-08 3
4 66 2017-04-06 2017-01-07 2
5 104 2017-05-07 2016-09-10 2
RoomReservation table
Roomid, reservationid
3 53
3 198
4 178
5 172
5 218
Room table
id, hotelid, Roomnumber, price
1 1 1.01 268.83
2 1 1.02 201.28
3 1 1.03 126.64
4 1 1.04 122.56
5 1 1.05 217.41
Now I am trying to make a query to which gives me an overview off income per hotel. So for each hotel I want to get the reservations, and do amount of persons * the price of the room for each room in the hotel.
I've tried different things without success, I read somewhere that I needed to use a subquery but I have no idea how.
I want it to look like;
Hotelname1; income
Hotelname2; income
Hotelname3; income
Hotelname4; income
Hotelname4; income
Why can't you just do this:
SELECT
Hotel.Name,
SUM(Room.Price*Reservation.Amountofpersons)
FROM
Hotel
JOIN Room
ON Hotel.HotelId=Room.HotelId
JOIN RoomReservation
ON Room.RoomId=RoomReservation.RoomId
JOIN Reservation
ON RoomReservation.ReservationId=Reservation.ReservationId
GROUP BY
Hotel.Name
You can try it whit this query:
select hotel.name,sum(reservation.amount*room.price)
from hotel_table as hotel
inner join room_table as room on (hotel.hotelid=room.hotelid)
inner join roomreservation_table as room_reservation on (room.roomid=room_reservation.roomId)
inner join reservation_table as reservation on (room.reservationId=reservation.reservationid)
group by hotel.hotelid

How to create a query using a view

How do I use the view I created to get different data outputs. I have created the view VJobCustomerLaborCost. This view gives each job for each customer with total of labor cost for each job. I need to get each customer with total labor cost for each customer. I have given the View and sample outputs.
GO
CREATE VIEW VJobCustomerLaborCost
AS
SELECT DISTINCT
TJ.intJobID
,TJ.strJobDescription
,TC.intCustomerID
,TC.strLastName + ', ' + TC.strFirstName AS strCustomerName
,SUM(TJE.intHoursWorked * TE.monHourlyRate) AS monTotalLaborCost
FROM
TJobs AS TJ
,TJobCustomers AS TJC
,TCustomers AS TC
,TJobEmployees AS TJE
,TEmployees AS TE
WHERE
TJ.intJobID = TJC.intJobID
AND TJC.intCustomerID = TC.intCustomerID
AND TJ.intCustomerID = TJC.intCustomerID
AND TJE.intJobID = TJ.intJobID
GROUP BY
TJ.intJobID
,TJ.strJobDescription
,TC.intCustomerID
,TC.strLastName
,TC.strFirstName
GO
This is the output from my view. This gives me all customers and each jobs total labor cost
intJobID strJobDescription intCustomerID strCustomerName monTotalLaborCost
----------- ------------------------- ------------------- ----------------- ---------------------
1 Kitchen Remodel 1 Belcher, Bob 8740.00
8 Basement Remodel 1 Belcher, Bob 13300.00
9 Bathroom Remodel 1 Belcher, Bob 12065.00
10 Roof Replacement 1 Belcher, Bob 3325.00
11 Living Room Remodel 1 Belcher, Bob 0.00
3 Bedroom Remodel 3 Parker, Peter 3800.00
6 Roof Replacement 3 Parker, Peter 0.00
7 Basement Remodel 3 Parker, Peter 1710.00
4 Bedroom Remodel 4 Solo, Hans 2850.00
5 Basement Remodel 2 Stark, Tony 0.00
What I need is to use the View created to get total labor cost for each customer. So output would be
intCustomerID strCustomerName monTotalLaborCost
------------------- ----------------- ---------------------
1 Belcher, Bob 37,430
3 Parker, Peter 5,510
4 Solo, Hans 2,850
2 Stark, Tony 0.00
How do I use the above view to get this output?
It looks like you need just to group and sum your data:
select
intCustomerID,
strCustomerName,
sum(monTotalLaborCost) as monTotalLaborCost
from VJobCustomerLaborCost
group by intCustomerID, strCustomerName

sql Query on effective date

I would like to get report for drink purchased in whole month but price of the drink can change any time in month and I would like to get report for a month with price change
I have two tables
SELECT [ID]
,[DrinkID]
,[UserID]
,[qty]
,[DateTaken]
FROM [Snacks].[dbo].[DrinkHistory]
SELECT [ID]
,[DrinkID]
,[UserID]
,[qty]
,[DateTaken]
FROM [Snacks].[dbo].[DrinkHistory]
[DrinkHistory]:
ID DrinkID UserID qty DateTaken
----------------------------------------------------------------------
1 1 1 1 2014-05-10
2 1 1 2 2014-05-15
3 2 1 1 2014-06-01
4 2 1 4 2014-06-01
5 1 1 3 2014-05-20
6 1 1 4 2014-05-30
[DrinkPricesEffect]:
PriceID DrinkID DrinkPrice PriceEffectiveDate IsCurrent
-----------------------------------------------------------------------------------
1 1 10.00 2014-05-01 1
2 1 20.00 2014-05-20 1
3 2 9.00 2014-06-01 1
4 2 8.00 2014-01-01 1
5 1 30.00 2014-05-25 1
6 1 40.00 2014-05-28 1
I would like to have result as under date taken between 2014-05-1 to 2014-05-31
DrinkId Qty Price DateTaken PriceEffectiveDate
-----------------------------------------------------------------------
1 1 10 2014-05-10 2014-05-01
1 2 10 2014-05-15 2014-05-01
1 3 20 2014-05-20 2014-05-20
1 4 40 2014-05-30 2014-05-28
Is there any who can give me some idea or write query for me?
If your drink price can change any time in a month you could additionaly save the price for each purchase. I would add a column [PricePaid] to the table [DrinkHistory].
When adding a record to [DrinkHistory], the price for the drink at the moment is known, but later it might change so you save the current price to the history...
Then for your result you could just display the Whole [DrinkHistory]
SELECT * FROM DrinkHistory;
This should work:
Select
DH.DrinkId,
DH.Qty,
DPE.DrinkPrice AS Price,
DH.DateTaken,
DPE.PriceEffectiveDate
FROM DrinkHistory DH
JOIN DrinkPricesEffect DPE ON DPE.PriceID =
(
Select Top 1 PriceID FROM
(
Select PriceID,RANK() OVER(ORDER BY PriceEffectiveDate DESC ) AS rnk
FROM DrinkPricesEffect
WHERE DH.DrinkId = DrinkId AND
DH.DateTaken >= PriceEffectiveDate
)SubQ WHERE rnk = 1
)
WHERE DH.DateTaken Between '2014-05-01' AND '2014-05-30'
Here you can find the SQL Fiddle link: http://sqlfiddle.com/#!6/5f8fb/26/0

Calculate value of percentage sql server [duplicate]

This question already has an answer here:
sql server calculate value according to pecentage and add and group them according to uid
(1 answer)
Closed 9 years ago.
I have this table.
orderid processid uid user processdesc companyname ordervalue perwet orgid
1 1 16 Damayanti Enquiry Synechron 33000 10.00 NULL
1 2 4 Meghana Requirement Synechron 33000 10.00 NULL
1 3 5 Yogini Proposal FollowUp Synechron 33000 10.00 NULL
1 4 5 Yogini Order Synechron 33000 20.00 NULL
1 5 4 Meghana Vendor Management Synechron 33000 10.00 NULL
1 6 1 anaghantech Collection Synechron 33000 20.00 NULL
2 1 4 Meghana Enquiry test 100000 10.00 NULL
2 2 4 Meghana Requirement test 100000 10.00 NULL
2 3 5 Yogini Proposal FollowUp test 100000 10.00 NULL
2 4 4 Meghana Order test 100000 20.00 NULL
2 5 4 Meghana Vendor Management test 100000 10.00 NULL
2 6 1 anaghantech Collection test 100000 6.67 NULL
2 6 4 Meghana Collection test 100000 6.67 NULL
2 6 16 Damayanti Collection test 100000 6.67 NULL
5 1 16 Damayanti Enquiry FASTER HYDRAULICS PVT. LTD. 700000 10.00 NULL
5 2 16 Damayanti Requirement FASTER HYDRAULICS PVT. LTD. 700000 10.00 NULL
5 3 16 Damayanti Proposal FollowUp FASTER HYDRAULICS PVT. LTD. 700000 10.00 NULL
5 4 16 Damayanti Order FASTER HYDRAULICS PVT. LTD. 700000 20.00 NULL
I want to add one more column to this table
like perwet/100 * ordervalue
using the query given below
SELECT a.orderid,
b.processid,
b.uid,
d.username,
c.processdesc,
a.companyname,
b.ordervalue,
b.perwet,
b.orgid
FROM ordermaster a,
temp_calpoints1 b,
process c,
userinfo d
WHERE a.orderid = b.orderid
AND c.processid = b.processid
AND d.uid = b.uid
ORDER BY b.orderid,
b.processid,
b.uid;
You can use VIEW instead of adding a new column to your table:
CREATE VIEW dbo.MyView
AS
SELECT a.orderid,
b.processid,
b.uid,
d.username,
c.processdesc,
a.companyname,
b.ordervalue,
b.perwet,
b.orgid,
MyField = b.perwet / 100 * b.ordervalue
FROM ordermaster a,
temp_calpoints1 b,
process c,
userinfo d
WHERE a.orderid = b.orderid
AND c.processid = b.processid
AND d.uid = b.uid