select max and min from multiple tables - sql-server

I am using SQL Server 2012. I have two tables that contain dates. I want to query the max and min dates from both tables. I know the line below will give me the max and min dates for one table.
select max(dtTime), min(dtTime) from tableOne
What I want to do is get the min of the two max dates from table one and two & the max of the two min dates from the table. Please see the example below.
TableOne TableTwo
Max Date 6-June-2000 23-June-2002
Min Date 10-Jan-1980 15-Feb-1982
Result I would like returned,
Max Date = 6-June-2000
Min Date = 15-Feb-1982

You can use UNION, and then select minimum from max values and max from minimum values:
SELECT min(mx), max(mn)
FROM (
SELECT max(dtTime) AS `mx`, min(dtTime) AS `mn` FROM tableOne
UNION
SELECT max(dtTime) AS `mx`, min(dtTime) AS `mn` FROM tablTow
) AS t1

select max(t1.dtTime), min(t2.dtTime) from tableOne as t1, tableTwo as t2

Related

Calculation of Average of distinct values

I have date in below format:
Now, I am want to display latest Post Date of each Account No, its corresponding amount, average of Amount of all previous dates including the latest date but the hack is I need to display latest Post Date based on ShareID.
I need the Amount of minimum ShareID and while taking average I have to omit amount of duplicate/same date of max(Postdate).
I need the data in below format:
You can try :
WITH
T1 AS
(
SELECT AccountNo, FundNo, MAX(PostDate) AS LastPostDate
FROM MyTable
GROUP BY AccountNo, FundNo,
),
T2 AS
(
SELECT DISTINCT AccountNo, FundNo, Amount
FROM MyTable
)
SELECT T1.AccountNo, T1.FundNo, T1.LastPostDate, T.PostDate, AVG(T2.Amount)
FROM T1
JOIN T2 ON T1.AccountNo = T2.AccountNo
JOIN MyTable AS T ON T.AccountNo = T1.AccountNo AND T.PostDate, = T1.LastPostDate
Post the DDL of your table and an example under a INSERT SQL statements to help us sto give a correct solution please.

SQL Server : Join If Between

I have 2 tables:
Query1: contains 3 columns, Due_Date, Received_Date, Diff
where Diff is the difference in the two dates in days
QueryHol with 2 columns, Date, Count
This has a list of dates and the count is set to 1 for everything. All these dates represent public holidays.
I want to be able to get the sum of QueryHol["Count"] if QueryHol["Date"] is between Query1["Due_Date"] and Query1["Received_Date"]
Result Wanted: a column joined onto Query1 to state how many public holidays fell into the date range so they can be subtracted from the Query1["Diff"] column to give a reflection of working days.
Because the 01-01-19 is a bank holiday i would want to minus that from the Diff to end up with results like below
Let me know if you require any more info.
Here's an option:
SELECT query1.due_date
, query1.received_date
, query1.diff
, queryhol.count
, COALESCE(query1.diff - queryhol.count, query1.diff) as DiffCount
FROM Query1
OUTER APPLY(
SELECT COUNT(*) AS count
FROM QueryHol
WHERE QueryHol.Date <= Query1.Received_Date
AND QueryHol.Date >= Query1.Due_Date
) AS queryhol
You may need to play around with the join condition - as it is assumes that the Received_Date is always later than the Due_Date which there is not enough data to know all of the use cases.
If I understand your problem, I think this is a possible solution:
select due_date,
receive_date,
diff,
(select sum(table2.count)
from table2
where table2.due_date between table1.due_date and table1.due_date) sum_holi,
table1.diff - (select sum(table2.count)
from table2
where table2.date between table1.due_date and table2.due_date) diff_holi
from table1
where [...] --here your conditions over table1.

SQL Server : update every 5 records with Past Months

I want to update 15 records in that first 5 records date should be June 2019,next 5 records with July 2019,last 5 records with Aug 2019 based on employee id,Can any one tell me how to write this type of query in SQL Server Management Studio V 17.7,I've tried with below query but unable to do for next 5 rows..
Like below query
Update TOP(5) emp.employee(nolock) set statusDate=GETDATE()-31 where EMPLOYEEID='XCXXXXXX';
To update only a certain number of rows of a table you will need to include a FROM clause and join a sub-query which limits the number of rows. I would suggest using OFFSET AND FETCH instead of top so that you can skip X number of rows
You will also want to use the DATEADD function instead of directly subtracting a number from the DateTime function GETDATE(). I'm not certain but I think your query will subtract milliseconds. If you intend to go back a month I would suggest subtracting a month rather than 31 days. Alternatively it might be easier to specify an exact date like '2019-06-01'
For example:
TableA
- TableAID INT PK
- EmployeeID INT FK
- statusDate DATETIME
UPDATE TableA
SET statusDate = '2019-06-01'
FROM TableA
INNER JOIN
(
SELECT TableAID
FROM TableA
WHERE EmployeeID = ''
ORDER BY TableAID
OFFSET 0 ROWS
FETCH NEXT 5 ROWS ONLY
) T1 ON TableA.TableAID = T1.TableAID
Right now it looks like your original query is updating the table employee rather than a purchases table. You will want to replace my TableA with whichever table it is you're updating and replace TableAID with the PK field of it.
You can use a ROW_NUMBER to get a ranking by employee, then just update the first 15 rows.
;WITH EmployeeRowsWithRowNumbers AS
(
SELECT
T.*,
RowNumberByEmployee = ROW_NUMBER() OVER (
PARTITION BY
T.EmployeeID -- Generate a ranking by each different EmployeeID
ORDER BY
(SELECT NULL)) -- ... in no particular order (you should supply one if you have an ordering column)
FROM
emp.employee AS T
)
UPDATE E SET
statusDate = CASE
WHEN E.RowNumberByEmployee <= 5 THEN '2019-06-01'
WHEN E.RowNumberByEmployee BETWEEN 6 AND 10 THEN '2019-07-01'
ELSE '2019-08-01' END
FROM
EmployeeRowsWithRowNumbers AS E
WHERE
E.RowNumberByEmployee <= 15

Set operators problem when trying to find MIN and MAX date for a condition

I want to find the minimum and maximum date on which a given product had a maximum unit cost, but only of the unit cost had a value of more than 10.
The result that I should get should be something like this:
If the date is the minimum date_type is MIN, and vice-versa.
This is the script that I tried, but I only get two records:
select MIN(dt) as min_date, MAX(dt) as max_date
from products
WHERE price = (SELECT max(price) FROM products where unit_id =1)
Products table:
Unit table:

A Way To Count Result Based on Date

SELECT
a.OrderSuffix AS 'OrderSuffix',
COUNT(1) AS 'CountNew'
FROM
dbo.Orders AS a,
dbo.OrderStatus AS b
WHERE
b.Status = 'Finished' AND
a.OrderSuffix IN ('ABC', 'DEF', 'HIJ')
GROUP BY
a.OrderSuffix
For this query above, I can get all total rows count for each order suffix. Is there a way to include a date as well?
E.g. I want to count all rows of 'ABC' whose dateField is greater than specifiedDate.
If you want to filter rows before you aggregate, you can just put it in your WHERE clause.
If you want the comparison to be based on the aggregate (e.g. groups with, say, a max dateField greater than some value) you can use the HAVING clause.

Resources