Trouble with a SQL using between and multiple occurences - mysql

everyone. I'm new here and I have a question on SQL which I seem to think that it may be easy to do in SQL but I'm out of ideas and I could use some help with my problem.
So I have a table (sql also here http://www.sqlfiddle.com/#!2/b9a37/1/0)
With multiple occurences for each person, different id's with auto increment and I have 3 fields, "Category", "In" and "Out"
What I'm trying to implement is a way for me to know when some of the users on the table belongs to the system using the "In" and "Out" as the limits.
Example
User A - Category A - IN 2002 OUT 2010
User A - Category B - IN 2011 OUT 9999
User B - Category B - IN 2002 OUT 2010
In the above example I would like to know who belongs to the system in year 2010:
so for User A, he Left Category A in 2010 but joined in 2011 Category 2011 so he SHOULD be a user in 2010 with Category A
for User B he should NOT belong to the system because there's no new entry for 2010+
At the end I'm tring to have the following output for 2010
Smith Category A
Pablo Category A
I'm not achieving the results I want, for example
SELECT * from users
WHERE (users.In<=2010 and users.Out=2010)
Outputs
Smith Category A In 2002 Out 2010
Roger Category B In 2002 Out 2010
Miller Category B In 2008 Out 2010
Pablo Category A In 2002 Out 2010
But Roger and Miller left the system in 2010 so they should NOT be members in 2010, and Smith and Pablo changed their category in 2010+ so they should show in the output.
A few notes:
Don't ask me why this solution is developed like this, I just stumbled on it and trying to solve this issue.
I'm considering doing a function in php do filter the data based on the requirements that I want because i'm running out of ideas to solve this.
If you find a way to implement this better than what I saw here, be my guest and i'm open to new ideas.
Thanks in advance.
Final Note:
Perhaps using http://www.sqlfiddle.com/#!2/b9a37/1/0 and try to find the desired output will help you out.

Give this one a shot:
select Name, Category
from users
where `In` <= 2010 and (
`Out` > 2010 or name in (
select name
from users
where `In` = 2011
)
)
SQL Fiddle Example

This appears to work:
select * from users a, users b where a.name = b.name and a.out + 1 = b.out
However, it will not work correctly if more than one user has the same surname and it assumes that the out year is one less than the in year.

Related

get sum of all the transactions of each user for specific month

I am working on small finance web app and I need to generate one monthly general report of all the users which shows a total of all the transactions made by each user during a month. the table structure is as below.
username amount date
-----------------------------
a 1000 2018-8-1
b 2000 2018-8-1
c 1500 2018-8-3
b 1700 2018-8-6
b 1100 2018-8-7
a 2000 2018-8-10
c 1600 2018-8-12
Need to get sum of each user's transactions during the month such as
a : 3000
b : 4800
c : 3100
Please help me to find out the sum using laravel query builder.
You can do this :
$user
->transactions()
->where('date', '>', Carbon::before())
->where('date', '<', Carbon::now())
->get(['user_id', 'amount'])
->sum('amount');
This considering you have a relationship between transactions and user models. You can adapt to your schema. But the pure MySQL solution that #Tim Biegeleisen linked may be more resources efficient.
You may also use whereBetween(), but check that it works correctly with dates.

ms access create report with two tables

I am needing to create a report between two tables. One table has ID, FirstName, LastName. The seconded table has NoteID, ID and Notes. There is a one to many relationship. Each person can have many notes. What I would like to do is fill a listbox or textbox with the notes that belong to that person.
On that note, how can I create a report that will display somewhat as the following:
First Name: Jeff Last Name: Smith
Notes:
This is note 1 for Jeff Smith
This is note 2 for Jeff Smith
This is note 3 for Jeff Smith
This is note 4 for Jeff Smith
First Name: Kim Last Name: Yung
Notes:
This is note 1 for Kim Yung
This is note 2 for Kim Yung
Thank you for any thing on this to lead me in the right direction.
Okay - so I made a query to use as the Record Source for the Report.
SELECT People.ID,
People.FirstName,
People.LastName,
Notes.NOTES
FROM People INNER JOIN Notes
ON People.ID = Notes.ID;
I clicked report design, set this query as the Record Source for the report.
I added a GROUPING on ID (this is to separate each person's Notes).
This created an ID HEADER, which is where you put FirstName, LastName, and your Notes label.
In the Detail section, you put the NOTES field from your query.
Output
If you have any other questions, let me know.
What you need is a Subreport. A Report that will have another report in it. This works in a similar way to a Main Form and Sub Form. More information is available on the MS Office website : https://support.office.com/en-ca/article/Create-and-use-subreports-816f987a-4615-4058-8f20-ce817093bb33

Filtering out some rows

I'd like to filter out some rows in SQL. This is my table.
ID | year
1 2002
1 2003
2 2003
2 2004
3 2002
I'd like to filter the ID's that has got a 2003 in the year column.
That means in this case, there will be no ID's that has got 2003 in the year column.
What is the SQL code I should use?
Your question is a bit ambiguous. One interpretation is to get the list of ids that do not contain the year 2003:
select id
from t
group by id
having sum(year = 2003) = 0
Have a look here http://www.sqlfiddle.com/#!2/bd0d6/3
select id
from dateyear
where year<> 2003
group by id
If you want to list all IDs that do not have a 2003 in the year column then year != 2003, as it was suggested by other users, won't be enough because that will return id = 2 as it contains 2004 too.
A good approach is to list get all IDs and remove from them the ones that contain 2003 in the year. You can do that this way:
SELECT DISTINCT id FROM t
WHERE id NOT IN (
SELECT id FROM t
WHERE YEAR = 2003
)
This will only output id = 3.
Fiddle here.

Expression total not displaying correct data in SSRS 2008

A long time reader. A great wealth of info on this site.
Hopefully this isn't a dumb question, but I've been struggling on how to get the correct totals in my report.
I'm having issues with simple totals. I have a report that takes the difference of two numbers and shows the result, with the results being both negative and positive. At the bottom of the report I want a total sum of the difference. The totals are not even close for some reason.
Here's my data:
Correct Data
Specialist Total Sales Budget Difference
DICK "$35,174.00" "$63,530.00" "($28,356.00)"
NATHAN "$16,193.00" "$40,000.00" "($23,807.00)"
PAUL "$52,096.00" "$55,000.00" "($2,904.00)"
STEVE "$31,185.44" "$66,700.00" "($35,514.56)"
**Totals: "$134,648.44" "$225,230.00" "($90,581.56)"**
Incorrect Data that is in my report
Specialist Total Sales Budget Difference
DICK "$35,174.00" "$63,530.00" "($28,356.00)"
NATHAN "$16,193.00" "$40,000.00" "($23,807.00)"
PAUL "$52,096.00" "$55,000.00" "($2,904.00)"
STEVE "$31,185.44" "$66,700.00" "($35,514.56)"
**TOTALS: "$134,648.44" "$225,230.00" "$71,118.44"**
As you can see, the data shows the total differece as $71,118.44 when it should be ($90,581.56).
Here is my expression to get the result of the Difference:
=Sum(Fields!TotalSales.Value)-Fields!Budget.Value
I right clicked on the text box and selected "Add Total" to get a Grand Total for the Difference field. I also tried this suggestion:
=Sum(Fields!TotalSales.Value)-Sum(Fields!Budget.Value)
And this:
=ReportItems!textbox14.Value - ReportItems!textbox15.Value
Another thing to mention is there is grouping on Specialist. The Total Sales field is a Group total for their sales for that particular month. The Budget field is a single field outside of the group.
This seems like a no brainer that it should work. Maybe someone can give me some guidance on this.
Thanks in advance.
EDIT:
Thanks for the help, but unfortunately the issue is more complicated than that :) I should have been more clear on that. I'm pulling data from 3-4 databases and they don't have a common field to link on. What I'm using a Row number to reduce duplicate subtotals and set them to 0. I using a rownumber on the Budget number, but the data I was getting back was bogus. Here's the data I have:
Name Team SubTotal Budget
SCOTT Vikings 202 25000.00
SCOTT Vikings 1890 25000.00
SCOTT Vikings 5167 25000.00
SCOTT Vikings 20256 25000.00
SCOTT Vikings 0 25000.00
SCOTT Vikings 0 25000.00
And here's the data I want to have:
Name Team SubTotal Budget
SCOTT Vikings 202 25000.00
SCOTT Vikings 1890 0.00
SCOTT Vikings 5167 0.00
SCOTT Vikings 20256 0.00
SCOTT Vikings 0 0.00
SCOTT Vikings 0 0.00
If the budget number repeats more than once, I want it to be 0. I think this is the reason my totals aren't showing correctly in SSRS. I'm calculating the Difference field by taking the GrandTotal of the Salesman's subtotals and subtracting them from the Budget Field that was put into the group footer (since I'm new I can't post images, sorry. Here's the hyperlink)
http://i55.tinypic.com/124jw2u.png
Here's my SQL Statement also:
WITH InvoicedAndPaid
AS
(
SELECT KEY1
,ltrim(rtrim(CustomText01)) as CustomText01
,ROW_NUMBER() OVER(PARTITION BY DocNo ORDER BY DocNo) AS RowNumber
,SubTotal
,OrderDate
,INVOICEDATE
FROM DocumentHeadersItems AS AA
JOIN SorArCombined AS BB
ON AA.DocNo = ('AA' + BB.CustomerPoNumber)
JOIN CONTACT1 AS CC
ON AA.SoldToCMAccountNo = CC.ACCOUNTNO
WHERE CreatedBy != 'NOAHDM'
AND KEY1 IN (#org)
AND SubTotal != 0
AND LEN(INVOICE) > 0
AND
(
(
CUSTOMER = 'QAA'
AND (INVOICEDATE IS NOT NULL)
AND (DATEPART(MM,INVOICEDATE) = DATEPART(MM,#start))
AND (DATEPART(YYYY,INVOICEDATE) = DATEPART(YYYY,#end))
)
OR
(
CUSTOMER != 'QAA'
AND (YearInvBalZero > 0)
AND (YearInvBalZero = DATEPART(YYYY,#start))
AND (MonthInvBalZero = DATEPART(MM,#start))
AND (YearInvBalZero = DATEPART(YYYY,#end))
AND (MonthInvBalZero = DATEPART(MM,#end))
)
)
)
SELECT bb.team_id
,bb.specialist_id
,dd.Budget
,cc.team_name
,KEY1
,CustomText01
,CASE WHEN RowNumber = 1 THEN SubTotal ELSE 0 END as SubTotal
FROM InvoicedAndPaid as aa
join SalesReporting.dbo.team_members as bb
on rtrim(aa.CustomText01) = rtrim(bb.specialist_name)
join SalesReporting.dbo.team_master as cc
on bb.team_id = cc.team_id
join SalesReporting.dbo.sales_goals as dd
on bb.specialist_id = dd.specialist_id
WHERE dd.time_span LIKE 'M%'
AND dd.month = DATENAME(MONTH,#end)
AND dd.Org = aa.KEY1
AND cc.team_name in (#team)
AND dd.period_no = DATEPART(MM,#end)
ORDER BY team_name, CustomText01
Does this help out a little? I'm trying to avoid doing a Stored Procedure because I'm fairly new at SSRS and SQL Server.
One option would be to calculate the total sales in the SQL Server query that is used in SSRS dataset. Following example shows a sample. The sample was created based on an assumption of how I envisioned the table might be. The report was created in SSRS 2008 R2 and database used was SQL Server 2008 R2.
Assuming that the source table is as shown in screenshot #1. The table is not normalized but it is shown here just for an example.
The query for the report database would be as shown in screenshot #2. The query is also given under SSRS Dataset Query section.
Report would be designed as shown in screenshot #3. Expression in section a would =Fields!TotalSales.Value - Fields!Budget.Value and Expression in section b would be =Sum(Fields!TotalSales.Value, "SalesData") - Sum(Fields!Budget.Value, "SalesData").
Screenshot #4 shows report execution.
Hope that helps.
SSRS DataSet Query:
SELECT Specialist
, SUM(Sales) AS TotalSales
, SUM(DISTINCT(Budget)) AS Budget
FROM dbo.SalesData
GROUP BY Specialist
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
In this rare case, I had to put in a footer and reference the sum formulas to the actual text boxes. Very weird that this worked but the regular expressions did not.
I appreciate your help on this!

querying same table twice

I have two tables. One is stock_by_month which keeps records on bookId, stockvalue and reportId. The second table is book; which keeps records on BookId,BookTitle and bookprice.
The reportId is unique for every different month, so for 2010 october is 1, 2010 november is 2 and 2010 december is 3
The Task is I want to generate a report which will include book details and also give the stock value of current month(reportid 3) and the previous month(reportId 2).
I am new to this sort of complexity. I am not sure if that is possible. if it is, I will be very grateful for any help. Thanks
Sounds like you want to use a join. There are plenty of tutorials on SQL out there, so read up on joins and you should see how you can implement your report.
You should join the two tables to get all the information, then group by the reportid. Below is some SQL to get you started but definitely read up on joins as Cameron suggested, and also on 'group by'
SELECT m.bookId, m.stockvalue, m.reportId, b.BookId, b.BookTitle, SUM(b.bookprice) AS total
FROM stock_by_month m
JOIN book b
ON b.PRIMARY_KEY = m.FOREIGN_KEY
GROUP BY m.reportId, m.bookId, m.stockvalue, b.BookId, b.BookTitle, b.bookprice
ORDER BY m.reportId DESC