SQL Query to pull the last four dates - sql

I am using SQL Server 2012 and trying to pull the 4 most recent order dates in a OrderDate column for certain members. I am not sure how to code for this. Any help will be greatly appreciated.

Order by date in descending order, and limit the number of rows to 4, like this:
select top 4 order_date from orders order by order_date desc
Optimizer will figure out that you have a limit, and optimize your query to avoid sorting the entire table. If order_date column is indexed, query optimizer would use index to get you four dates without going to the table itself.

It should be something similar to this:
select top 4 o.OrderDate
from Members m
inner join Orders o
on m.ID = o.MemberID
where <your certain members criteria>
order by o.OrderDate desc

I'd do something like this (you didn't provide table structure, so this is just pseudo-code).
Create empty table TempOrders to store top orders for each member
Open Cursor to go through all member Ids
For each #MemberId insert into TempOrders select top 4 * from orders where MemberId = #MemberId order by OrderDate desc
your result is in TempOrders table

Related

How to order Order Date by Order Count SQL?

This might be a silly newbie question, but I am trying to figure out how to order something.
How would you construct an SQL statement so that in a table ORDERING with an ORDERDATE attribute I can see how many orders placed on each date?
I know that the following query makes it so it is organized by the date but I want to know how many duplicates for each date in order to find how many orders placed in a day.
SELECT *
FROM ORDERING
ORDER BY ORDERDATE DESC;
Count is an aggregate function, so you have to GROUP BY the attribute you want to aggregate.
SELECT ORDERDATE,COUNT(*)
FROM ORDERING
GROUP BY ORDERDATE
ORDER BY ORDERDATE DESC;
en making questiuons.
SELECT ORDERDATE,COUNT(*)
FROM ORDERING
GROUP BY ORDERDATE
HAVING COUNT(*)>1

PostgreSQL how to compare a column's numeric value against the SUM of another numeric value?

I am new to PostgreSQL and restored this Database in order to practice my Queries. It contains the following Tables:
What is the best query to find how many orders have an order_total that is less than the sum of their line_total(s)?
This is the query I have but I doubt that my number is accurate. I feel like I am doing something wrong:
select COUNT(order_total) from orders
join order_lines
on orders.id = order_lines.order_id
having count(order_total) < sum(line_total)
Am I querying correctly or not?
Thanks
Pill
perhaps something like this
select o.order_total,sum( l.line_total) as sum_line_total
from orders o join order_lines l on o.orders.id=l.order_id
group by o.order_total
having o.order_total < sum(l.line_total)
That answer gave more than one result. I experimented and came across the correct answer by using the following sub-query:
select count(*) from orders,
(Select order_id, sum(line_total) from order_lines group by order_id) a
where order_total < a.sum and order_id = orders.id;
Thanks though for the response
Pill

How to use ORDER BY in a Stored Procedure

I have the following code:
use Northwind
go
create procedure CalcStatistics
#year int = 0
as
if exists
(select * from sysobjects
where name = 'Statistics' and type = 'U')
drop table Statistics
select YEAR(ORDERS.OrderDate) As [Year],
DATEPART(qq, OrderDate) As [Q],
SUM (Freight) As [Freight],
into Statistics
from ORDERS, ORDERDETAILS
where ORDERS.OrderID = ORDERDETAILS.OrderID
AND YEAR(ORDERS.OrderDate) = #year
group by YEAR(ORDERS.OrderDate),
DATEPART(qq, OrderDate)
order by YEAR(ORDERS.OrderDate)
exec CalcStatistics 1997
select *
from Statistics
I would like to make it so that the query prints the year and quarter of that year in ascending order, but when I try the old fashioned "order by DATEPART(qq, OrderDate)" it doesn't seem to affect the outcome of the query. How do I solve this, and why does my method not work?
I would like to make it so that the query prints the year and quarter of that year in ascending order,
Based on this statement, you need two keys in the ORDER BY. One method uses the aliases, instead of the expressions. This is simpler:
order by [Year], [Q]
Another trick when using dates is to order by the MIN() (or MAX()) of the dates:
order by MIN(ORDERS.OrderDate)
EDIT:
I think I see the problem. You are putting this data into a table called statistics, not looking at the results from the query itself. Then you are presumably running a query like this:
select s.*
from statistics s;
If so, the results are not in order. The results from a SQL query are unordered unless the query specifies the ordering. So:
select s.*
from statistics s
order by [Year], [Q];

Which customer has placed most orders. SQL query

I'm trying to query my database for my class to find out which customer has placed the most orders. The table I'm searching is a three attribute table that has the customerID, orderID, and the placedDate.
The query I thought would work is:
select cid from placed order by sum(oid);
But I keep getting an error saying cid is "not a single-group group function" the oid is the primary key and is a foreign key that references another table. Is that what the issue is?
If you want to count the number of orders you should do a count instead of a SUM:
SELECT cid,COUNT(*)
FROM placed
GROUP BY cid
ORDER BY COUNT(*) DESC
This will give you the list of customers and their respective number of orders, ordered by the number of orders descendent.
If you want just the customer with most orders, you have to limit the number of records to the first one. For that, you have to tell what DBMS you use, since it varies with the DBMS the way you limit the query to the first one (ex: mysql is LIMIT 1, sql-server is TOP 1):
In Oracle, you can do:
SELECT * FROM (
SELECT cid,COUNT(*)
FROM placed
GROUP BY cid
ORDER BY COUNT(*) DESC
) a
WHERE rownum = 1
In case the there are one or more customers having maximum orders:
select * from orders o, customer c where o.cusId = c.cusId and o.cusId IN (select cusId from orders group by cusId having count(*) = (select count(*) from orders or group by or.cusId order by count(*) desc limit 1));
This solution is for MySQL, as I have used LIMIT. It can be changed as per the DBMS.
I also used = in the second query since LIMIT does not work with IN.

Finding Most Recent Order for a Particular Item

I'm trying to write a SQL Query for DB2 Version 8 which retrieves the most recent order of a specific part for a list of users. The query receives a parameter which contains a list of customerId numbers and the partId number. For example,
Order Table
OrderID
PartID
CustomerID
OrderTime
I initially wanted to try:
Select * from Order
where
OrderId = (
Select orderId
from Order
where
partId = #requestedPartId# and customerId = #customerId#
Order by orderTime desc
fetch first 1 rows only
);
The problem with the above query is that it only works for a single user and my query needs to include multiple users.
Does anyone have a suggestion about how I could expand the above query to work for multiple users? If I remove my "fetch first 1 rows only," then it will return all rows instead of the most recent. I also tried using Max(OrderTime), but I couldn't find a way to return the OrderId from the sub-select.
Thanks!
Note: DB2 Version 8 does not support the SQL "TOP" function.
Try the following one. I didn't test it. The idea is that you first find all orders for all your specified customers. These will be grouped and you find the biggest order time for each customer (combination of group by and max). This is the foo query, that identifies the records that you need. Than you join it with your order table to retrieve the necessary information for these orders.
select o.*
from order o inner join
(select customerId, max(orderTime)
from order o
where customerId in ( #customerIds#)
and partId = #requestedPartId#
group by customerId) foo
on o.customerId = foo.customerId
and o.orderTime = foo.orderTime
EDIT: The above query gives you the most recent order for each customer you specified under the condition, that there is only one order per customer and orderTime. To get only one order it is slightly different. The following example assumes that the orderTime is unique, meaning there are no two orders at the same time in the database. This is generally be true if orderTime is recorded in milliseconds.
select o.*
from order o inner join
(select customerId, max(orderTime)
from order o
where customerId in ( #customerIds#)
and partId = #requestedPartId#) foo
on o.orderTime = foo.orderTime