Select top * from 2 table orderb by some field - sql-server

I have 2 table like this
[Info]
[Score]
I want to select top3 * orderby score in May DESC
the result should be look like this.

Try a JOIN on both tables in a derived table with a SUM on Score and order on that
SELECT TOP 3 *
FROM(
SELECT
I.User_Id, I.[Name], I.Age, Score = SUM(S.Score)
FROM
Info I
INNER JOIN
Score S On S.User_Id = I.User_Id
WHERE MONTH(S.[DATE]) = 5 --May (however I suspect this might not be a DATE object)
GROUP BY
I.User_Id, I.[Name], I.Age
) X
ORDER BY X.Score DESC

Here you go, You can use join statement.
SELECT TOP(3) a.user_id, a.Name, a.Age, b.Score FROM Users a JOIN Score b On a.user_id=b.user_id Order By b.Score desc

The following will be helpfull.
SELECT TOP 3 S.User_Id, SUM(S.Score) Score, U.Name, U.Age
FROM Info U
INNER JOIN Score S ON U.User_Id = S.User_Id
WHERE MONTH(S.Date) = 5 --Only May Month.
GROUP BY S.User_Id, U.Name, U.Age
ORDER BY 2 DESC

Related

Get Max value for each User in a specific period SQL

I have the following query:
I am trying to select for each ACCOUNT_ID in the Table PAYMENT its maximum AMOUNT value.
It gives me a result but I suspect I am missing ACCOUNT_ID rows (I should get more ACCOUNT_ID)
SELECT a.REQUEST_DATE as PartyID, a.AMOUNT
FROM admin_all.PAYMENT a
LEFT OUTER JOIN admin_all.PAYMENT b
ON a.ACCOUNT_ID = b.ACCOUNT_ID AND a.AMOUNT < b.AMOUNT
WHERE b.ACCOUNT_ID IS NULL and a.TYPE='DEPOSIT' and a.STATUS='COMPLETED'
and (a.REQUEST_DATE between '2019-12-01' and '2019-12-17')
Can anybody indicate if my select is correct?
Maybe something like this
SELECT a.ACCOUNT_ID, MAX(a.AMOUNT)
FROM admin_all.PAYMENT a
WHERE a.TYPE='DEPOSIT' and a.STATUS='COMPLETED'
and (a.REQUEST_DATE between '2019-12-01' and '2019-12-17')
GROUP BY a.ACCOUNT_ID
--You can USE ROW_NUMBER() with OVER and PARTITION BY to break up the records
--into numbered rows ordered by the highest AMOUNT (DESC) and partitioned by the ID
--Then grab each record with a ROWNUM = 1
SELECT x.[PartyID], x.[AMOUNT]
FROM
(
SELECT a.REQUEST_DATE as PartyID, a.AMOUNT, ROW_NUMBER() OVER (PARTITION BY a.ACCOUNT_ID ORDER BY a.AMOUNT DESC) AS [RowNum]
FROM admin_all.PAYMENT a
LEFT OUTER JOIN admin_all.PAYMENT b
ON a.ACCOUNT_ID = b.ACCOUNT_ID AND a.AMOUNT < b.AMOUNT
WHERE b.ACCOUNT_ID IS NULL and a.TYPE='DEPOSIT' and a.STATUS='COMPLETED'
and (a.REQUEST_DATE between '2019-12-01' and '2019-12-17')
) AS x
WHERE x.[RowNum] = 1

SQL Query Group by Count and Left Join Tables

i need your help! I got some simple SQL skills, but this query kills me...
My Tables
Now i want the TOP5 WorkTimes on the Equipment (What Equipment got the longest WorkTime).
I want this OUTPUT:
MY Query:
SELECT
Equipment, EquipmentName, count(Equipment) as Count
FROM
Operations o
LEFT JOIN Orders ord ON ord.Id = o.[Order]
LEFT OUTER JOIN Equipments e ON ord.Equipment = e.EquipmentNumber
GROUP BY
Equipment, EquipmentName
ORDER BY Count DESC;
Another Question is how i can show o.Worktime?
i got an error with GroupBy...
please help me Thanks!
You can try this query:
select equip_nr,
(select equipmentname from table_equipments where equipmentnr = [to].equip_nr) equip_name,
sum(timeInMins) / 60.0 Worktime
from (
select (select equipmentnr from table_orders where id = [to].[order]) equip_nr,
case when workunittime = 'RH' then worktime * 60 else worktime end timeInMins
from table_operations [to]
where exists(select 1 from table_orders
where [to].[order] = id
and location = '152')
and [start] >= '2018-07-01 00:00:00.000' and [start] < '2018-08-01 00:00:00.000'
) [to] group by equip_nr
By the way, LEFT JOIN is equivalent to LEFT OUTER JOIN.
Just use SUM(worktime) as aggregate function, instead of COUNT(Equipment)
SELECT
e.[ID_Equipment]
, Name
, SUM( IIF(o.WorkUnitTime='MIN', worktime/60.0, worktime) ) as WorktimeMIN
FROM
Operations o
LEFT JOIN Orders ord ON ord.ID_Order = o.ID_Order
LEFT OUTER JOIN Equipment e ON ord.ID_Equipment = e.ID_Equipment
GROUP BY
e.[ID_Equipment]
, Name
ORDER BY
WorktimeMIN DESC
See SQL Fiddle here: http://sqlfiddle.com/#!18/5b5ed/11

select count over partition by

I am learning window functions in sql server. I am using AdventrueWorks2012 database for practice. I want to calculate total number of sales and purchases for each item in the store.
The classic solution can be like
SELECT ProductID,
Quantity,
(SELECT Count(*)
FROM AdventureWorks.Purchasing.PurchaseOrderDetail
WHERE PurchaseOrderDetail.ProductID = p.ProductID) TotalPurchases,
(SELECT Count(*)
FROM AdventureWorks.Sales.SalesOrderDetail
WHERE SalesOrderDetail.ProductID = p.ProductID) TotalSales
FROM (SELECT DISTINCT ProductID,
Quantity
FROM AdventureWorks.Production.ProductInventory) p
Trying to convert to window functions gives me wrong results:
SELECT DISTINCT d.ProductID,
Quantity,
Count(d.ProductID)
OVER(
PARTITION BY d.ProductID) TotalPurchases,
Count(d2.ProductID)
OVER(
PARTITION BY d2.ProductID) TotalSales
FROM (SELECT DISTINCT ProductID,
Quantity
FROM AdventureWorks.Production.ProductInventory) p
INNER JOIN AdventureWorks.Purchasing.PurchaseOrderDetail d
ON p.ProductID = d.ProductID
INNER JOIN AdventureWorks.Sales.SalesOrderDetail d2
ON p.ProductID = d2.ProductID
ORDER BY d.ProductID
Why this is wrong? How can I correct it?
You should change INNER JOIN to LEFT JOIN
Because when you inner join, result will miss productid which from ProductInventory table does not have PurchaseOrderDetail or SalesOrderDetail.

How to group by month of a date using a function in a select statement

I am having problems grouping by the month of a date when using a function. It was working before but the query was less complicated as I am now using a function that uses a rolling year from the current month. Here is my code.
SELECT
CASE
WHEN DATEDIFF(mm,dbo.fn_firstofmonth(getdate()), dbo.fn_firstofmonth(D.expected_date)) < 12
THEN DATEDIFF(mm,dbo.fn_firstofmonth(getdate()), dbo.fn_firstofmonth(D.expected_date)) + 1
ELSE 13 END AS [Expected Month],
P.probability AS [Category], COUNT(O.id) AS [Customers]
FROM opportunity_probability P
INNER JOIN opportunity_detail D ON D.probability_id = P.id
INNER JOIN opportunities O ON D.opportunity_id = O.id
INNER JOIN
(
SELECT opportunity_id
FROM opportunity_detail
GROUP BY opportunity_id
) T ON T.opportunity_id = O.customer_id
GROUP BY P.probability, MONTH(D.expected_date)
ORDER BY P.probability, MONTH(D.expected_date)
It works if I have D.expected_date in the GROUP BY but I need to group on the MONTH of this date as it does not bring through the data correctly.
You could always remove the group by, then put your entire select into another select, and than group by the outer select:
select t.A, t.B from (select A, datepart(month, b) as B) t group by t.A, t.B
This way you can address your month field as if it where a normal field.
Example is far from complete, but should get you on your way.
You can try to find month by this code:
GROUP BY P.probability, DATEPART(month, D.expected_date)
try this
SELECT
to_char(D.expected_date, 'YYYY-MM'),
CASE
WHEN DATEDIFF(mm,dbo.fn_firstofmonth(getdate()), dbo.fn_firstofmonth(D.expected_date)) < 12
THEN DATEDIFF(mm,dbo.fn_firstofmonth(getdate()), dbo.fn_firstofmonth(D.expected_date)) + 1
ELSE 13 END AS [Expected Month],
P.probability AS [Category], COUNT(O.id) AS [Customers]
FROM opportunity_probability P
INNER JOIN opportunity_detail D ON D.probability_id = P.id
INNER JOIN opportunities O ON D.opportunity_id = O.id
INNER JOIN
(
SELECT opportunity_id
FROM opportunity_detail
GROUP BY opportunity_id
) T ON T.opportunity_id = O.customer_id
GROUP BY P.probability, to_char(D.expected_date, 'YYYY-MM')
ORDER BY P.probability, to_char(D.expected_date, 'YYYY-MM')

create sql query to fetch repeat column values within time frame

Can someone help me with this query? I want to get the result of all the customer_id which repeats more than once in 24hrs
SELECT
O.Order_No, O.Customer_ID, O.DateOrdered, O.IPAddress,
C.FirstName, C.LastName, CD.nameoncard
FROM
Order_No O
INNER JOIN
CardData CD ON O.card_id = CD.id
INNER JOIN
Customers C ON O.customer_id = C.customer_id
ORDER BY
O.order_no desc
adding more details..
so suppose order with customer id xx was placed on 04/23 2:30 pm and again 2nd order was placed with same customer Id xx on same day 04/23 5:30 pm.
i want the query to return me customer Id xx
Thanks
select Customer_ID, CAST(DateOrdered as Date) DateOrdered, count(*) QTDE
from Order_No
group by Customer_ID, CAST(DateOrdered as Date)
having count(*) > 1
To get the customers who have orders issued after the first one, then you could use the following query:
select distinct A.Customer_ID
from Order_No A
inner join (select Customer_ID, min(DateOrdered) DateOrdered from Order_No group by Customer_ID ) B
on A.Customer_ID = B.Customer_ID
and A.DateOrdered - B.DateOrdered <= 1
and A.DateOrdered > B.DateOrdered
SQL Fiddle
To get all customers that have ANY TIME more than one order issued in period less or equal than 24h
select distinct A.Customer_ID
from Order_No A
inner join Order_No B
on A.Customer_ID = B.Customer_ID
and A.DateOrdered > B.DateOrdered
and A.DateOrdered - B.DateOrdered <= 1
SQL Fiddle
Self-join:
SELECT distinct O.Customer_ID
FROM
Order_No O
inner join Order_No o2
on o.customerID = o2.customerID
and datediff(hour, o.DateOrdered, o2.DateOrdered) between 0 and 24
and o.Order_No <> o2.Order_No
This will return all customer_IDs that have ever placed more than one order in any 24 hour period.
Edited to add the join criteria that the matching records should not be the same record. Should return customers who placed two different orders at the same time, but not customers who placed only one order.

Resources