Data between two dates using where condition - sql-server

I'am Using a stored procedure to retrieve values between data using Where condition(related to particular Person not the one related to Date).
E.g I have table with cols
User Name User ID date_used Book Name
xxxx UID001 12-03-2012 zzzzz
yyyy UID002 14-03-2015 ccccc
xxxx UID001 14-03-2015 rrrrr
Desired Out put
User Name User ID date_used Book Name
xxxx UID001 12-03-2012 zzzzz
xxxx UID001 14-03-2015 rrrrr
For this I tried below way, please help me where i'm wrong
SELECT UserID,Issue_Date,Book_Name FROM dbo.Books
where UserID = #userID and Issue_Date >= #From and Issue_Date <= #To
order by Issue_Date Desc
#From(datetime) and #to(datetime) are datepickers value(startDate and EndDate)
#userID varchar
When i remove UserID clause I was able to retrive all the books issued for all the users. but when i add a where clause of user id no rows are reflected.
Please advice me on this with other methods to get this done.

Related

SQL First and Last Transaction Report

I have a table in SQL, that looks a little similar to the table below:
[enter image description here]
My goal is to generate a first and Last Transaction report.
I want to know when did customer X make their first purchase and what is the date of their most recent purchase.
I would like to group my results by Store and add all the transaction if they happen on the same day.
For instance, if John do made 2 expenses at walmart on Jan 15th and that's their most recent transaction, I would like those two expenses to be Summed in my report.
Here is the final result I'd expect from a table like on the example above:
[enter image description here]
With what I have tried so far,
I am only getting 1 value back
The SQL looks a little similar to
Select
SN
, SID
, CustomerName
, BankAccount
, Min(TransDate)
, Max(TransDate)
, price
, store
From transaction
GROUp by
SN
, SID
, CustomerName
, BankAccount
, Min(TransDate)
, Max(TransDate)
, price
, store
I know I have to use some types of nested query to get the result(maybe) but I have been unsuccessful.
I would try and pull out the customer info you need to filter out the rest of the data. I would start with a CTE to get the MIN and MAX dates for each customer. I would then JOIN that back up to the original table and just get the records for the Customer that are on that MAX date.
I would assume you have something that is more Unique then the customer name, and if so I would use that instead. But here is what I came up with given the data you provided:
CREATE TABLE #tmp(SerialNumber int, SearialID int,CustomerName varchar(100), BankAccount int,
TranDate date, Price decimal(10,2),TracerID int,Store varchar(20))
INSERT INTO #tmp VALUES
(2,2,'Peter Smith',14564,'1/1/2021',10,756,'Kroger'),
(1,1,'John Do',12345,'1/1/2021',10,156,'Walmart'),
(1,1,'John Do',12345,'1/15/2021',5,148,'Walmart'),
(1,1,'John Do',12345,'1/15/2021',15,148,'Walmart'),
(2,2,'Peter Smith',14564,'1/12/2021',12,756,'Kroger')
;WITH CTE AS
(
SELECT Min(TranDate) FirstDate, Max(TranDate) LastDate, CustomerName
FROM #tmp
GROUP BY CustomerName
)
SELECT T.SerialNumber,T.SearialID,T.CustomerName,t.BankAccount,C.FirstDate FirstTrans, C.LastDate,SUM(t.Price) Price,T.Store
FROM #tmp T
INNER JOIN CTE C on t.CustomerName = c.CustomerName and t.TranDate = c.LastDate
GROUP BY T.SerialNumber,T.SearialID,T.CustomerName,t.BankAccount,C.FirstDate,C.LastDate,T.Store

Replacing data in one table with data in another table using a unique ID

I'm using Access 2016 to view data from a table on our SQL server. I have a massive audit log where the record being viewed is represented by a "FolderID" field. I have another table that has values for the FolderID (represented as "fid") along with columns identifying the record's name and other ID numbers.
I want to be able to replace the FolderID value in the first table with CUSTOMER_NAME value from the second table so I know what's being viewed at a glance.
I've tried googling different join techniques to build a query that will accomplish this, but my google-fu is weak or I'm just not caffeinated enough today.
Table 1.
EventTime EventType FolderID
4/4/2019 1:23:39 PM A 12345
Table 2
fid acc Other_ID Third_ID CUSTOMER_NAME
12345 0 9875 12345678 Doe, John
Basically I want to query Table 2 to search for fid using the value in Table 1 for FolderID, and I want it to respond with the CUSTOMER_NAME associated with the FolderID/fid. The result would look like:
EventTime EventType FolderID
4/4/2019 1:23:39 PM A Doe, John
I'm stupid because I thought I was too smart to use the freaking Query Wizard. When I did, and it prompted me to create relationships and actually think about what I was doing, it came up with this.
SELECT [table1].EventTime, [table1].EventType, [table1].FolderID, [table1].ObjRef, [table1].AreaID, [table1].FileID, [table2].CUSTOMER_NAME, [table2].fid FROM [table2]
LEFT JOIN [table1] ON [table2].[fid] = [table1].[FolderID];
You can run this query and check if it helps!.
Select EventTime, EventType , CUSTOMER_NAME AS FolderID FROM Table1, Table2 Where Table1.FolderID = Table2.fid;
Basically, 'AS' is doing what you want here as you can rename your column to whatever you want.

Problèm with SQL select grouping

I have a small problem with a SQL Server query.
I have an issue with my view of several base tables with duplicate values, so far no problem, these duplicates are logical. By unfortunately I do not get the desired end result, I could do it by programming the front end of my application but I would prefer to do the work on the server.
I will explain the principle:
I have 30 companies which each have an employee table.
My view is a union of the 30 employee tables.
Each employee has a unique serial number, the number is the same across tables, so an employee named "John Doe" with an ID number 'S0000021' can be hired in Company A then transferred to company Q without any problems, it will retain the serial number 'S0000021'.
The difference between the data from the Employee tables A and Q will be in this example the start (hire) and release (transfer) dates entered for Company A and just the start date for company Q so the view will have 2 lines for "John Doe".
12 common fields are the following:
Serial Number (Identical in every employee table)
Social Security Number (Same in every employee table)
Start/Hire Date
Release/Transfer date (empty/null if the employee is current)
Name (Can change across companies if the person divorces)
First name
Maiden name
Last Name
Gender
Final Released
Company Code
The problem seems simple that I would not appear that the latest information of the employee, except with a group by, if it has changed name or release date, it will be displayed twice.
I tried the following different ways but they don't return what I want
I returned results both ways but I always see duplicates because my dates within companies are never identical, and their name may change.
Sorry for this Google translation.
1 --
select
vue.matricule,
vue.numsecu,
vue.name,
vue.lastname,
vue.maidenname,
vue.secondname,
vue.genre,
vue.released,
vue.companycode
from
vue
group by
vue.matricule,
vue.numsecu,
vue.name,
vue.lastname,
vue.maidenname,
vue.secondname,
vue.genre,
vue.released,
vue.companycode
2---
select
distinct(vue.matricule),
vue.numsecu,
vue.name,
vue.lastname,
vue.maidenname,
vue.secondname,
vue.genre,
vue.released,
vue.companycode
from
vue
I assumed the following:
there is a view (vue) that already gathers all data from each of the 30 companies
you are just looking for the latest record for each employee
If you need to also see a record for each name change we can change this.
--set up test data
declare #vue table (
matricule varchar(20),
numsecu varchar(20),
name varchar(20),
lastname varchar(20),
maidenname varchar(20),
secondname varchar(20),
genre varchar(20),
start datetime,
released datetime,
companycode varchar(20));
insert #vue values
('S0000021','123456789','John', 'Doe',null,null,'M','2015-01-01','2015-12-31','A'),
('S0000021','123456789','Johnny', 'Doe',null,null,'M','2016-01-01',null,'Q'), --new company, name change, currently employed
('S0000022','123456780','Jane', 'Doe',null,null,'M','2015-01-01','2015-12-31','A'),
('S0000022','123456780','Jane', 'Doe',null,null,'M','2016-01-01','2016-02-01','Q'); --new company, name change, terminated
select * from #vue order by matricule, start;
--get latest record for each employee
select *
from (--add row numbering
select *, row_number() over (partition by matricule order by start desc) row_num
from #vue
) vue2
where vue2.row_num = 1;

SQL scheduled jobs Failed Notification

I need idea or a way to check if my schedule jobs work and insert the right data. I Have a function that call a stored procedure to count inserted data from today and insert into specific field.
like this
SET #male = (select count(idUser) from (select idUser from #tmpLog2 where sex = 1 AND CAST(catchTime as date) = #DATE group by idUser)u);
SET #female = (select count(idUser) from (select idUser from #tmpLog2 where sex = 0 AND CAST(catchTime as date) = #DATE group by idUser)u);
INSERT INTO CatchLog
(
[male],
[female]
)
VALUES
(
#male,
#female
)
the stored procedure works OK, but sometime when today have a lot of data, the result inserted 0 for male / female.
It's possible to have 0 data inserted when today data really no male / female.
but sometime it inserted 0 but there are male n female data. Anyone can help me to check, how to check if the data inserted true and give some report or insert into error Log if data inserted not true?
sorry for my bad english
I dont know what column are you using into Count() Function. But if you are using Nullable column into it then it may gives 0 even if record were added as column value is null.
Consider to use Primary key column or not Nullable column in count() argument.

Advanced SQL Server stored procedure?

I have one table in my database that I want to update each year. I need to pull two of the column values from my asp.net page and populate the rest from my database already.
I have a budget table for each year, the year updates automatically on my page according to the month of the year. When the month changes to a specific month I need the stored procedure to update itself to add the budget items with a blank amount so that I can enter the amounts manually.
Old Data:
Year Code1 Code1Description Code2 Code2Description BudgetAmt($750.00) Initials
New Data:
NewYear Code1 Code1Description Code2 Code2Description BudgetAmt($0.00) Initials
This so that when I enter editmode on my gridview the codes will already be there just with blank budgetamt for me to update. Does this make sense? Is it something that is possible?
You are having the webpage call the stored procedure? In which case simply create a table with the item codes you want to be populated:
ALTER PROCEDURE [dbo].[stp_TemplateSPROC]
(#year as int) AS
INSERT tbl_webpage (Year, code1, code1desc, code2, code2desc, spending, Initials)
Select
#Year [Year], code1, code1desc, code2, code2desc,
0 as spending, '' as Initials
from tablewithcodesin
This, when called, would populate a table with the Year, codes, and zeros/blanks for you to fill in.
tablewithcodesin would just be Code1 Code1Description Code2 Code2Description

Resources