Getting a count while accounting for an attribute - sql

I have two tables, one for account information and one for customer information. An account can have multiple customers associated with it. What I want to do is grab all active customers in a given month. However, I also want to account for customers who are active and purchased in earlier months.
Account
ID IND_ID LAST_PURCHASE
1 101 2013-01-15
2 102 2013-03-20
2 103 2013-02-05
3 104 2013-07-25
4 105 2012-01-11
Customer
ID STATUS
101 A
102 A
103 A
104 E
105 A
Select just the active customers is not the issue as I can just filter on that column. However, how can I select the count of active 'customers' while accounting for people who purchased in the past two month.

You can do this by looking at the maximum purchase date and filtering on that:
select c.id
from customer c join
account a
on c.id = a.ind_id
where c.status = 'A'
group by c.id
having max(last_purchase) >= date_add(month, -2, getdate());

Related

MS Access SQL, How to return only the newest row before a given date joined to a master table

I have two tables in a MS Access database as shown below. CustomerId is a primary key and fkCustomerId is a foreign key linked to the CustomerId in the other table.
Customer table
CustomerId
Name
1
John
2
Bob
3
David
Purchase table
fkCustomerId
OrderDate
fkStockId
1
01/02/2010
100
3
08/07/2010
101
2
14/01/2011
102
2
21/10/2011
103
3
02/03/2012
104
1
30/09/2012
105
3
01/01/2013
106
1
18/04/2014
107
3
22/11/2015
108
I am trying to return a list of customers showing the last fkStockId for each customer ordered before a given date.
So for the date 01/10/2012, I'd be looking for a return of
fkCustomerId
Name
fkStockId
1
John
105
2
Bob
103
3
David
104
A solution seems to be escaping me, any help would be greatly appreciated.
You can use nested select to get last order date.
SELECT Purchase.fkCustomerId,
Name,
fkStockId
FROM Purchase
JOIN
(
SELECT fkCustomerId,
MAX(OrderDate) as last_OrderDate
FROM Purchase
WHERE OrderDate < '01/10/2012'
GROUP BY fkCustomerId
) AS lastOrder
ON lastOrder.fkCustomerId = Purchase.fkCustomerId
AND last_OrderDate = OrderDate
LEFT JOIN Customer
ON Customer.CustomerId = Purchase.fkCustomerId
This example assumes OrderDate before '01/10/2012'. You might need to change it if you want it to be filtered by a different value.
Another assumption is that there's only one corresponding fkStockId for each OrderDate

New to SQL - How to compare data from two sets of joined tables

I'm trying to compare a set of multiple tables against another set of multiple tables in a SQL database. Admittedly, I'm very novice to SQL so please forgive me if my terminology is incorrect.
I have 6 individual tables in my database. 3 of those are comprised of current month's data and the other three are prior month's data. I need to produce a report that shows current month data, but also compare the account balance against the prior month - I need to create a column that will list "true" or "false" based on whether the account balances match.
I have joined the three current month's data tables together and I have joined the three prior month's data tables together.
The two sets of tables are identical. Below is a description of the tables - There is one set prefixed "CURRENT" and one prefixed "PRIOR":
BALANCE:
EntityID
AccountID
AccountBalance
ENTITY:
ID
Label
Description
ACCOUNT:
ID
AccountNumber
Description
The report I need to provide should list the following from the current month's data:
Label
Description
AccountNumber
AccountDescription
AccountBalance
I need to add a column called "Changed" at the end of the report. This column should have a "True" or "False" value depending on whether or not the current & prior account balances match.
Thus far, I have only been able to join the tables. I'm unsure how to edit this query to compare the current month dbo.CURRENT_BALANCE.AccountBalance against the prior month's dbo.PRIOR_BALANCE.AccountBalance
SELECT DISTINCT
dbo.CURRENT_ENTITY.Label,
dbo.CURRENT_ENTITY.Description AS Entity,
dbo.CURRENT_ACCOUNT.AccountNumber,
dbo.CURRENT_ACCOUNT.Description AS AccountDescription,
dbo.CURRENT_BALANCE.GLAccountBalance
FROM
dbo.CURRENT_BALANCE
INNER JOIN dbo.CURRENT_ENTITY ON dbo.CURRENT_BALANCE.EntityID = dbo.CURRENT_ENTITY.ID
INNER JOIN dbo.CURRENT_ACCOUNT ON dbo.CURRENT_BALANCE.AccountID = dbo.CURRENT_ACCOUNT.ID
CROSS JOIN dbo.PRIOR_BALANCE
INNER JOIN dbo.PRIOR_ENTITY ON dbo.PRIOR_BALANCE.EntityID = dbo.PRIOR_ENTITY.ID
INNER JOIN dbo.PRIOR_ACCOUNT ON dbo.PRIOR_BALANCE.AccountID = dbo.PRIOR_ACCOUNT.ID
The query above returns my expected results:
Label Entity AccountNumber AccountDescription AccountBalance
21 Company ABC 1 Customer Sales 25
21 Company ABC 2 Customer Sales 568
22 XYZ Solutions 3 Vendor Sales 344
23 Number 1 Products 4 Vendor Sales 565
24 Enterprise Inc 5 Wholesale 334
24 Enterprise Inc 6 Wholesale 5452
24 Enterprise Inc 7 Wholesale 5877
26 QWERTY Solutions 8 Customer Sales 456
27 Acme 9 Customer Sales 752
28 United Product Solutions 10 Vendor Sales 87
What I would like to do is have a result similar to:
Label Entity AccountNumber AccountDescription AccountBalance Changed
21 Company ABC 1 Customer Sales 25 FALSE
21 Company ABC 2 Customer Sales 568 FALSE
22 XYZ Solutions 3 Vendor Sales 344 FALSE
23 Number 1 Products 4 Vendor Sales 565 FALSE
24 Enterprise Inc 5 Wholesale 334 TRUE
24 Enterprise Inc 6 Wholesale 5452 FALSE
24 Enterprise Inc 7 Wholesale 5877 TRUE
26 QWERTY Solutions 8 Customer Sales 456 FALSE
27 Acme 9 Customer Sales 752 FALSE
28 United Product Solutions 10 Vendor Sales 87 FALSE
I have no idea where to go from here. Would appreciate any advise from this group!
The below should work as a way to compare the 2 values.
I have added aliases to table names to help with reading;
SELECT DISTINCT
ce.Label
,ce.Description AS Entity
,ca.AccountNumber
,ca.Description AS AccountDescription
,cb.GLAccountBalance
,CASE
WHEN cb.GLAccountBalance = p.PriorBalance THEN 'False'
WHEN cb.GLAccountBalance <> p.PriorBalance THEN 'True'
END AS [Changed]
FROM dbo.CURRENT_BALANCE cb
INNER JOIN dbo.CURRENT_ENTITY ce ON cb.EntityID = ce.ID
INNER JOIN dbo.CURRENT_ACCOUNT ca ON cb.AccountID = ca.ID
LEFT JOIN ( SELECT DISTINCT
pe.ID AS PE_ID
,pa.ID AS PA_ID
,pb.GLAccountBalance AS PriorBalance
FROM dbo.PRIOR_BALANCE pb
INNER JOIN dbo.PRIOR_ENTITY pe ON pb.EntityID = pe.ID
INNER JOIN dbo.PRIOR_ACCOUNT pa ON pb.AccountID = pa.ID
) p ON p.PE_ID = ce.ID AND p.PA_ID = ca.ID

insert duplicate rows in temp table

i'm a new to sql & forum - need help on how to insert duplicate rows in temp table. Would like to create a view as result
View - Employee:
Name Empid Status Manager Dept StartDate EndDate
AAA 111 Active A111 Cashier 2015-01-01 2015-05-01
AAA 111 Active A222 Sales 2015-05-01 NULL
I don't know how to write a function, but do have a DATE table.
Date Table: (365 days) goes up to 2018
Date Fiscal_Wk Fiscal_Mon Fiscal_Yr
2015-01-01 1 1 2015
Result inquiry
How do i duplicate rows for each record from Employee base on each of the start date for entire calendar year.
Result:
Name Empid Status Manager Dept Date FW FM FY
AAA 111 Active A111 Cashier 2015-01-01 1 1 2015
AAA 111 Active A111 Cashier 2015-01-02 1 1 2015
******so on!!!!!!
AAA 111 Active A222 Sales 2015-05-01 18 5 2015
AAA 111 Active A222 Sales 2015-05-02 18 5 2015
******so on!!!!!!
Thanks in advance,
Quinn
Select * from Employee cross join Calendar.
This will essentially join every record in calendar to every record in Employee.
so, if there are 2 records in Employee and 10 in calendar, you'll end up with 20 total, 10 for each.
What you are looking for is a join operation. However, the condition for the join is not equality, because you want all rows that match between two values.
The basic idea is:
select e.*, c.date
from employee e join
calendar c
on e.startdate >= c.date and
(e.enddate is null or c.date <= e.enddate);
modified query - this yields result of previous & most recent records
select e.*, c.date, c.FW, c.FM, c.FY
from employee e
join calendar c
on e.startdate <= c.date and
ISNULL(e.enddate,GETDATE()) > c.date

Concatenating data from one row into the results from another

I have a SQL Server database of orders I'm struggling with. For a normal order a single table provides the following results:
Orders:
ID Customer Shipdate Order ID
-----------------------------------------------------------------
1 Tom 2015-01-01 100
2 Bob 2014-03-20 200
At some point they needed orders that were placed by more than one customer. So they created a row for each customer and split the record over multiple rows.
Orders:
ID Customer Shipdate Order ID
-----------------------------------------------------------------
1 Tom 2015-01-01 100
2 Bob 2014-03-20 200
3 John
4 Dan
5 2014-05-10 300
So there is another table I can join on to make sense of this which relates the three rows which are actually one order.
Joint.Orders:
ID Related ID
-----------------------------------------------------------------
5 3
5 4
I'm a little new to SQL and while I can join on the other table and filter to only get the data relating to Order ID 300, but what I'd really like is to concatenate the customers, but after searching for a while I can't see how to do this. What'd I'd really like to achieve is this as an output:
ID Customer Shipdate Order ID
----------------------------------------------------------------
1 Tom 2015-01-01 100
2 Bob 2014-03-20 200
5 John, Dan 2014-05-10 300
You should consider changing the schema first. The below query might help you get a feel of how it can be done with your current design.
Select * From Orders Where IsNull(Customer, '') <> ''
Union All
Select ID,
Customer = (Select Customer + ',' From Orders OI Where OI.ID (Select RelatedID from JointOrders JO Where JO.ID = O.ID)
,ShipDate, OrderID
From Orders O Where IsNull(O.Customer, '') = ''

sql query to link two tables

I have a table called users where the employee data are stored.
Also I have another table payment_details where employee's payment related data are stored
the two tables are as follows.
this table is users
sr_no emp_no username payment
1 1001 leroy <null>
2 1003 harry <null>
3 1004 Tom <null>
4 1008 Jon <null>
This table below is payment_details
sr_no name number month status date
43 Jon 1008 January paid 5/16/2012
44 Jon 1008 January balance 5/16/2012
45 Harry 1003 January paid 5/16/2012
46 Tom 1004 January paid 5/16/2012
47 leroy 1001 January paid 5/16/2012
48 Jon 1008 January paid 5/16/2012
49 Harry 1003 January paid 5/16/2012
50 Jon 1008 February balance 5/16/2012
51 leroy 1001 February paid 5/16/2012
52 Jon 1008 February paid 5/16/2012
53 Tom 1004 February balance 5/16/2012
My question here is to update "users" table payment column to "paid" when the status of his/her is all paid in payment_details table
You can either do this: http://www.sqlfiddle.com/#!3/db13f/18
update users set payment = 'paid'
from
(
select number
from payment_details
group by number
having sum(case when status = 'paid' then 1 end)
= count(*)
) as x
where x.number = users.emp_no;
Or this: http://www.sqlfiddle.com/#!3/db13f/19
update users
set payment = x.upd
from
(
select u.emp_no,
case when sum(case when d.status = 'paid' then 1 end) = count(*) then
'paid'
else
null
end as upd
from users u
left join payment_details d
on d.number = u.emp_no
group by u.emp_no
) as x
where x.emp_no = users.emp_no;
Their difference is how many rows it updates. On the second query, it updates all users, regardless if the user has a paid all status('paid') or not(null); on the first query, it updates only those who are paid.
The advantage of the second query, is when you change one of the all 'paid' status on payment_detail of a given user to 'not paid' for example, it can revert back the user's payment status to null
UPDATE order_details
SET payment= 'paid'
WHERE not EXISTS (SELECT 1
FROM payment_details
WHERE payment_details.emp_no= order_details.emp_no
AND payment_details.status <> 'paid'
)
There also simple way to get the value of particulars table into variable and update the tabe as below:
declare #bb varchar(50)
select #bb= status from payment_details where name=#name and id=#id
update uuser set payment = #bb
where name = #name and id=#id