Elixir, database, restore data every single month do default - database

I do have a database structure denoted like that:
schema "users" do
field :april, :integer
field :august, :integer
field :december, :integer
field :february, :integer
field :january, :integer
field :july, :integer
field :june, :integer
field :march, :integer
field :may, :integer
field :name, :string
field :november, :integer
field :october, :integer
field :points, :integer
field :role, :string
field :september, :integer
field :surname, :string
end
And I would like to clear one column every single month, for each user. This column is :points. By clear I mean set up value 0. By default the :points value is set up to 0.
I would like also to update each month every column in range :January - :December to value 50, which is set up also by default.
I know how to get a month from the date, but how could I by every single month restore to default values those columns? here is my migration file:
create table(:users) do
add :name, :string
add :surname, :string
add :role, :string
add :points, :integer, default: 0
add :january, :integer, default: 50
add :february, :integer, default: 50
add :march, :integer, default: 50
add :april, :integer, default: 50
add :may, :integer, default: 50
add :june, :integer, default: 50
add :july, :integer, default: 50
add :august, :integer, default: 50
add :september, :integer, default: 50
add :october, :integer, default: 50
add :november, :integer, default: 50
add :december, :integer, default: 50
end

You can do some limited introspection on the Ecto schemas to see what they have defined as the default value for a field by calling the __struct__/0 function. It will yield some information about the struct's default values:
MyEctoSchema.__struct__()
|> Map.from_struct()
However, whatever values the Ecto struct has are NOT guaranteed to be what is defined inside the database. Remember, there is no requirement for a database to have migrations at all, and the Ecto schemas have no inherent knowledge of how the database may be defined. In other words, it's entirely possible for the migrations to say one thing, the database to say another, and the Ecto schema struct to be defined with yet something different: although they might be strongly aligned, they're all operating independently and they are not sharing any information.
I wrote a package that helps inspect schemas that may be useful: https://hexdocs.pm/inspecto/
Once you have a value, then you can update your records using a standard Ecto update operation.
Unrelated: is there a better name for this table? It seems like it's storing summaries of monthly points, not really anything about "users" at all.

It sounds like you want a function to execute and detect the start of a month and update the database. That's my interpretation. Adjust the code below if that's not quite right:
defmodule Mateusz do
#months ~w(january february march april may june july august september october november december)a
#start_month_value 50
def start_month(users) do
if NaiveDateTime.utc_now().day == 1 do
users.points == 0
for month <- #months, do: users[month] == #start_month_value
users
end
Presumably you'll want to put the value users back in the database. I'll let you decide if that should be done in the function or by the caller.
As data structures go it might be cleaner for you if you created a months structure and declare an instance of the structure in the users structure. This would allow you to have default values for just the months fields and on the first just reset users.months to new(Months).

Related

How to count the particular values in the field in Google Data Studio

I am trying to create a simple table in Google Data Studio, which fetches data from MySql table. For example,
"Peter
John
Mike
Peter
George
Peter"
The above are the set of values in a field,
Here I have to count the number of "Peter" in the field and display the count.
Is it possible to display the count of particular values from a single field? If so, what function should I apply to get the required output?
I would suggest using a REGEXP_MATCH function to create a new field. Try this:
Create new field called Peter Count and use this formula:
CASE
WHEN REGEXP_MATCH(FIELD_NAME, "Peter") THEN 1
ELSE 0
END
Make sure the new field has a field type of Number and aggregation of SUM
Create a scorecard in your report and select your new field as the metric.
That should add up the occurrences of Peter and ignore other names.

Google Datastudio: Apply Date Range Filter for Two Different Date Columns of Date Source

I have a requirement to have date range filter which can be used for two different date columns of the data source(One at a time either through radio button to choose at which column date range should apply).
Is it possible to achieve this in Google Data studio ?
Workaround:
The general idea is to use let the user set the value of a parameter, which determines the value of a dummy field containing the value of either datetime column. You can then indicate that your table/chart should filter by this datetime field.
Create a parameter in the data source, with the names of the columns you want as possible values. If you want to filter the order_date and completed_date columns, these should be possible options.
Allow the user to set the parameter (e.g. by using a radio button).
Create a calculated field in the data source (e.g. select_date) which, depending on the value of the parameter. For example, create a field user_field:
CASE user_select # this is a parameter
WHEN "order_date" THEN order_date # this is the value of the order_date field
WHEN "completed_date" THEN completed_date # this is the value of the completed_date field
ELSE NULL
END
Set the 'Date Range Dimension' of your chart/table to user_field (the name of the calculated field).
Workaround:
If the table has a primary key, you can make a datablending with itself and in a data set put as a time filter a first field and in the other with the second field.
Example
After that, you should add the metrics and dimensions you need from one of them.
Now when you apply a time filter, it will work on both of them.

Enforcing a unique combination relationship in fields

Summery: I need any combination of [Field_1] and [Field_2] to be unique and for that uniqueness to be enforced. Note: This is not for permutations - and that's the difficulty.
In Depth:
I'm trying to track contacts for vendor software. I've set my DB up in the time old fashion such that a Vendor record may have many contacts. The trick is that contacts may be related to each other and may not be related to the parent vendor record. An example:
1. SuperBrokenSoftware is a tool who's vendor I need to contact all the time.
2. WeMakeBadSoftware is the Vendor
3. Fred works for WeMakeBadSoftware
4. Gale works for WeHelpPeopleWhenOthersWont
Let's say Gale is the appropriate contact to fix my issue with the SuperBrokenSoftware.
There is no way using the current hierarchy to track Gales relationship to SuperBrokenSoftware.
My solution is to keep track of these relationships in a table like so:
Field1 Field2 Field3
Fred Gale Gale handles specific issues for Fred
However given this solution Field_1 and Field_2 must be unique in combination. That is to say the records:
Field1 Field2 Field3
Fred Gale "Gale handles specific issues for Fred"
Gale Fred "Gale is awesome - Fred sucks"
Should be viewed as the same. Record 2 should not be allowed in the database because it is not unique.
What I have Tried:
Using the bijective - Szudzik's function: a >= b ? a * a + a + b : a + b * b; where a, b >= 0
I can calculate a unique identifier for every combination - but access cannot enforce uniqueness on a calculated field.
What is the best way to enforce a combination in Access?
Thanks in advance!!!
Create new field for unique identifier with unique index and create Before Change data macro, which should insert/change calculated identifier in new field.
Unique key can be just sorted concatenation of field1 and field2

MS Access Age Calculation across tables

I'm editing a database template so I can track differences in patient tests across age for the same person.
I retro-fit the "Student Database" template to utilize the forms and macros already created.
I have a patient table that stores all data collected at initial intake : name, date of birth (DOB), etc. and a second table that would track test scores across visits that includes : name, date of visit (DOV) and score information. These are paired so I can pull up information from one patient and see their scores across visits.
What I need to do now is create a query where I can calculate their age when they took the tests.
To do so, I have used expression builder and entered Calculated:([Visit Date]-[DOB])/365
This works for calculating age only if I re-enter the DOB in a new column on the patient visit table
I've tried using DateDiff and using [Patient]![DOB] to recall the data from the other table but I get the same error.
(Calculated age: ([Patient Visit]![Visit Date]-[Patients]![DOB])/365)
Calculated age: (DateDiff("yyyy",[Patients]![DOB],[Patient Visit]![Visit Date]))
Both spit out the error : Enter Parameter Value 'Patients!DOB'
If I enter a date, all data points and patients calculated to have the same DOB that I entered.
How do I let Access know I need it to calculate the date at visit for the DOB of the same patient?
?: Do I need to create a lookup table for the patient ID to match with the DOB and then use that field for calculation?
If there is something wrong with the expression I can fix, that would be ideal. If not, what is the best way to calculate age at visit without having to manually enter in the patient DOB more than once (once in initial uptake and again at each visit).
Thank you in advance.
I found a solution!
I was using 'query' wrong. instead of trying to force it to recognize another table, I needed to add the table to the query upon query creation.
i.e.:
1_ selected 'Query Design'
2_ selected the tables with the required information (entered through forms)
3_ Used `
Patient Name: IIf(IsNull([Last Name]),IIf(IsNull([First Name]),[First Name]),IIf(IsNull([First Name]),[Last Name],[First Name] & " " & [Last Name]))
`
for the first field and
Patient Visit.*
for the second field. By adding "Patient Visit.*" the query will add all fields from the table into the query.
The third field I selected DOB from the Patients table (it was available for selection because I had the two tables selected in the layout initially).
I am now able to use the original
Calculated:([Visit Date]-[DOB])/365
for age calculation w/o any error. I finalized formatting under properties > format > fixed.
Wooo!

Select exclusively a field from a table

I have to add a coupon table to my db. There are 3 types of coupons : percentage, amount or 2 for 1.
So far I've come up with a coupon table that contains these 3 fields. If there's a percentage value not set to null then it's this kind of coupon.
I feel it's not the proper way to do it. Should I create a CouponType table and how would you see it? Where would you store these values?
Any help or cue appreciated!
Thanks,
Teebot
You're correct, I think a CouponType table would be fit for your problem.
Two tables: Coupons and CouponTypes. Store the CouponTypeId inside the Coupons table.
So for an example, you'll have a Coupon record called "50% off", if would reference the percent off CouponType record and from there you could determine the logic to take 50% off the cost of the item.
So now you can create unlimited coupons, if it's a dollar amount coupon type it will take the "amount" column and treat it as a dollar amount. If it's a percent off it will treat it as a percentage and if it's an "x for 1" deal, it will treat the value as x.
- Table Coupons
- ID
- name
- coupon_type_id # (or whatever fits your style guidelines)
- amount # Example: 10.00 (treated as $10 off for amount type, treated as
# 10% for percent type or 10 for 1 with the final type)
- expiration_date
- Table CouponTypes
- ID
- type # (amount, percent, <whatever you decided to call the 2 for 1> :))
In the future you might have much more different coupon types. You could also have different business logic associated with them - you never know. It's always useful to do the things right in this case, so yes, definitely, create a coupon type field and an associated dictionary table to go with it.
I would definitely create a CouponType lookup table. That way you avoid all the NULL's and allow for more coupon types in the future.
Coupon
coupon_id INT
name VARCHAR
coupon_type_id INT <- Foreign Key
CouponType
coupon_type_id INT
type_description VARCHAR
...
Or I suppose you could have a coupon type column in your coupon table CHAR(1)

Resources