Listing Unmatched Positions out of One Table where reference date is specific - sql

I am pretty new to SQL, but i need to use it for my new job as the project requires it and as I am a non-IT-guy, it is more difficult for me, because thats my first time I work professionally with SQL.
Hopefully you can help me with it: (Sry for my english, i am a non-native speaker)
I need to start a query where I get unequal IDs from 2 different reference dates.
So I have one Table with following data:
DATES ID AMOUNT SID
201910 122424 99999 1
201911 41241242 99999 2
201912 12412424 -22222 3
...
GOAL:
So the ID's from the DATE: 201911 shall be compared with those from 201910
and the query should show me the unequal ID's. So only the unmatched ID's shall be displayed.
Out of this query, the Amount should be summed up and grouped into SIDs.

If you have two dates and you want sids that are only on one of them, then:
select sid
from t
where date in (201911, 201910)
group by sid
having count(distinct date) = 1;

Related

Query with two different where conditions

I have a table books where users donate number of books:
username books date
____________________________________
Jon 3 2017-06-12
Jon 2 2017-05-20
Mary 4 2017-05-12
I want something like
username This month Previous Month
_______________________________________________
Jon 3 2
You will need some kind of grouping or conditional sum operations. The simplest way to get the result in your question - though which may not actually scale to your needs - is:
select username
,sum(case when dateadd(datediff(month,0,[date]),0) = dateadd(datediff(month,0,getdate()),0) then books else 0 end as ThisMonth
,sum(case when dateadd(datediff(month,0,[date]),0) = dateadd(datediff(month,0,getdate())-1,0) then books else 0 end as PreviousMonth
from books
where username = 'Jon'
group by username
Obviously with more details in your question you could get a better suited answer and one that is not specific to SQL Server should you be on a different DBMS. That said, the conditional and date logic is the same in all other DBMS implementations, you may just need to change the function names.
This works by adding the number of months between an arbitrary start date (the 0s in the functions above) and a date value to get the date at the start of the month. The dates returned by this logic for both your date value and today (the getdate() function) will return the same start of the month where they are both within the same calendar month. By adding one less month (the -1 in the script above) you get the start of last month, which you can then also compare to your date value to get the number of books for last month.
The sum and group by is there to 'flatten' your data into the one row per username value.

Select all records from specified day

I have table named table_food in db with columns: first name, last name, date, food name. I want a query that returns all food names from specified date.
For example my table records looks like:
John Watson 2016-08-22 steak
John Watson 2016-08-22 burger
John Watson 2016-08-23 fries
John Watson 2016-08-23 apple
and I want to get all food names from 2016-08-23. How should I create my query?
I´m just assuming you´re using a MySQL-Database. The answer may vary for other databases.
There are two versions, depending on what you´re trying to get.
If you just want a list of all foods, including duplicates, you could use:
select food_name from table_food where date = '2016-08-23'
If you just need to get distinct values (each food name once) you could use:
select distinct(food_name) from table_food where date = '2016-08-23'
The first question could be: Which meals have been served and how many of them?
The second question could be: Which meals have been served at all (no matter how often)
It depends from the database you use.
I added also a distinct because I imagine that you need only distinct values of food names.
For MySql
select distinct(food_name) from table_food
where date = '2016-08-23'
For Oracle
select distinct(food_name) from table_food
where date = to_date('2016-08-23', 'YYYY-MM-DD')
Check for dialects of other databases.
Note that if the data stored in the date column has also hours, minutes and seconds you need a different query to extract data, for example in oracle:
select distinct(food_name) from table_food
where trunc(date) = to_date('2016-08-23', 'YYYY-MM-DD')
$date = "2016-08-23";
SELECT * FROM `table_food` WHERE `date` = '{$date}';
The reason I'd variable the date is solely down to as and when you wish to change the date. Don't get me wrong either of the above you can do. My personal preference would be to adjust the variable rather than the query.
When you need to retrieve data from a table, you'll have to specify what field you need to select from what table, under one or several conditions.
Since your condition is the date,
we'll use this syntax:
We added the word distinct in case you didn't need redundancy.
Select distinct FoodName
from Table_Food
Where date = '2016-08-23'

SQL Query with Results with different where clauses

I tried searching for an answer to this question...I may not be wording my search correctly as I am not a super guru in SQL.
Situation:
Microsoft SQL Server 2008 R2 database, two tables I'm interested in right now, call them OpenOrders and InvoicedOrders.
I want to pull OpenOrders for the month, quarter, and year, and then InvoicedOrders for the month, quarter, and year, grouped by sales zone (sales zone in the same table).
I can't post an image, but if you imagine we have 5 sales zone, and then the 6 date ranges noted above, there would be 7 rows and 5 columns in the query result. shown in text below if displays correctly.
1 10000 40000 12500 53200 12500 61180
2 23000 53000 25500 70490 25500 81063.5
3 45000 75000 47500 99750 47500 114712.5
4 43000 73000 45500 97090 45500 111653.5
5 76000 106000 78500 140980 78500 162127
What I want to do is a solution that is ideally one query, or a few queries, not 6 queries. I will be using this query in an SSRS report and was not successful with nested queries as those queries returned the 'returned more than one result' error.
I am now thinking of using a temp table to select the first row, insert into temp table, select second row, insert into temp table, then select all results from temp table and drop temp table.
Hope I provided enough info!
Is a temp table an ideal solution, or is there a better one out there?
Thanks for any help!
If you are trying to get one result set back, consider creating a view and use UNION to join the results for these different queries inside. You can then run a select to get results from the view like a table.

SQL change over time query

I have created 2 tables. one table has 4 fields. a unique name, a date and 3 figures. The second table contains the same fields but records the output of a merge function. therefore has a date at which time the update or insert function happened. what I want to do is retrieve a sum of either the difference between 2 days or alternatively the totals of the 2 days to work out how much the value has changed over the day. The merge function only updates if a value has changed or it needs to insert a new value.
so far I have this
select sum(Change_Table_1.Disk_Space) as total,
Change_Table_1.Date_Updated
from VM_Info
left join Change_Table_1
on VM_Info.VM_Unique = Change_Table_1.VM_Unique
where VM_Info.Agency = 'test'
group by Change_Table_1.Date_Updated
but this would just return the sum of that days updated total rather than the difference between the two days. One answer to this question would be to to add all new records to the table but this would contain a number of duplicates. So in my head what I want it to do is loop over the current figures for the day then loop over the next day but also to include all values that haven't updated. sorry if I haven't explained this well. so what I want to achieve is to get some sort of change of the total over time. If its poor design im in a position to accept that also.
Any help is much appreciated.
maybe this would explain it better. show me total for day 1, if the value hasn't changed then show me the same value for day 2 if it has changed show me new value. and so on...
ok to further elaborate.
the Change_Table looks like
vm date created action value_Field1 value_field_2 Disk_Space
abc 14/10/2013 insert 5 5 30
def 14/10/2013 insert 5 5 75
abc 15/10/2013 update 5 5 75
so the out put I want is for the 14th the total for the last column is 105. On the 15th abc has changed from 30 to 75 but def hasn't changed but still neds to be included giving 150
so the output would look like
date disk_Space
14/10/2013 105
15/10/2013 150
Does this help? If not, can you provide a few rows of sample data, and an example of the desired result?
select
(VM_Info.Disk_Space - Change_Table_1.Disk_Space) as DiskSpaceChange,
Change_Table_1.Date_Updated
from
VM_Info
left join Change_Table_1 on VM_Info.VM_Unique = Change_Table_1.VM_Unique and VM_Info.Date = Change_Table_1.Date_Updated
where
VM_Info.Agency = 'test'

Number of absent rows in daterange

I have a table with following structure
transaction_id user_id date_column
1 1 01-08-2011
2 2 01-08-2011
3 1 02-08-2011
4 1 03-08-2011
There can be at-max only one entry for each user on each date.
How can get all rows where user_id is not present for specific date range.
So for above table with user_id= 2 and date range 01-08-2011 to 03-08-2011, I want
result
02-08-2011
03-08-2011
Right now, I am using for loop to loop over all dates in given date range.
This is working fine with small date range, but I think it will become resource heavy for large one.
As suggested in a comment, create a table with the dates of interest (I'll call it datesofinterest). Every date from your date range needs to be put into this table.
datesofinterest table
--------------
date
--------------
01-08-2011
02-08-2011
03-08-2011
Then the datesofinterest table needs to be joined with all the userids -- this is the set of all possible combinations of dates-of-interest and userids.
Now you have to remove all those dates-of-interest/userids that are currently in your original table to get your final answer.
In relational algebra, it'd be something like:
(datesofinterest[date] x transaction[user_id]) - (transaction[date_column, user_id])
This page may help with translating '-' to SQL. Generating dates to populate the datesofinterest table can be done in SQL, manually, or with a helper program (perl's DateTime)