I have two tables:
create table dbo.Dates (
Id int not null
constraint Dates_Id_PK primary key clustered (Id),
[DateValue] date not null
}
create table dbo.Posts (
Id int identity not null
constraint Posts_Id_PK primary key clustered (Id),
Created datetime not null,
Title nvarchar (200) not null
)
For these tables I have Date and Post entities.
How can I get a table that has the column DateValue from Dates and the number of Posts with that date.
I need to match the datetime Created value to the date DateValue.
Thank you,
Miguel
I assume your Posts have dates with times, so you'll have to truncate them to the date part (as in the Date property of a DateTime):
from d in context.Dates
select new {
Date = d.DateValue,
NrOfPosts = (from p in context.Posts
where EntityFunctions.TruncateTime(t.Created) == d.DateValue
select p).Count()
}
you can use anonymous types. try the following snippet.
DateTime dateToMatch = GetDateToMatch();
using(YourEntities context = new YourEntities())
{
var result = context.Dates.Where(d => d.DateValue == dateToMatch)
.Select(d => new { Date = d.DateValue, PostCount = d.Posts.Count() });
}
Related
I'm running a SELECT using WHERE on gorm but the results are comming with the columns store_name and type empty(""). I have the following struct on Go:
type Store struct {
ID uint
StoreName string
Type string
Code string `gorm:"unique"`
Active bool
CreatedAt *time.Time
UpdatedAt *time.Time
}
The following database on Postgres:
CREATE TABLE IF NOT EXISTS stores
(
id BIGSERIAL PRIMARY KEY,
store_name TEXT NOT NULL,
type TEXT NOT NULL,
code TEXT NOT NULL UNIQUE,
active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
);
Im running this select right here:
var store Store
result := db.First(&stores).Where("code = ?", code)
if err := result.Error; err != nil {
return nil, err
}
return &stores, nil
Does anyone know what I may be doing wrong? All columns are returned on the SELECT except for the columns StoreName and Type. Thank you so much in advance!
You need to set the field tag if field name differs from DB column name.
Example:
StoreName string `gorm:"column:store_name"`
See this document: https://gorm.io/docs/models.html
I have a numeric(10,2) data type column named "Value" in a Payment table in postgresql Database.
CREATE TABLE IF NOT EXISTS PAYMENT(
PAYMENT_ID BIGINT NOT NULL DEFAULT nextval('payment_seq') PRIMARY KEY,
DATE TIMESTAMP,
PLACE VARCHAR(255),
VALUE NUMERIC(10,2) NOT NULL,
UTILISATEUR_ID BIGINT REFERENCES UTILISATEUR
);
I want to retrieve that numeric value by a BigDecimal Data Type in Java. (dto)
import java.math.BigDecimal;
public interface UserSumByGroup {
public String getFullName();
public BigDecimal getSumOfValues();
}
For some reason all the times the return values for the dto is null when I execute in the controller..
...
List<UserSumByGroup> usersGroupSumPaymnt = userRepo.userGroupSumPaymt();
model.addAttribute("userGroupListSumPaymt", usersGroupSumPaymnt);
System.out.println("usersGroupSumPaymnt=> "+usersGroupSumPaymnt.get(0).getSumOfValues());
...
SQL Query:
SELECT usr.FULL_NAME as fullName, SUM(VALUE) as paymentCount
FROM PAYMENT pym left join UTILISATEUR usr ON usr.utilisateur_id = pym.utilisateur_id
WHERE MONTH(pym.date) = MONTH(CURRENT_DATE)
AND YEAR(pym.date) = YEAR(CURRENT_DATE)
AND pym.utilisateur_id IN (1,5)
GROUP BY pym.utilisateur_id, usr.FULL_NAME;
Console Log:
usersGroupSumPaymnt=> null
Do you have some idea why I got always a Null?.
Thanks.
To correspond the names of the variables between Spring JPA and the Database, the names of the attributes of the dto object must be the same to the name of the result field in the query.
The name of the result query "paymentCount" needs to be the same as the dto instance "sumOfValues".
So, Change:
SUM(VALUE) as paymentCount
By
SUM(VALUE) as sumOfValues
I am using sqlx to create a go api.
I want to insert a record in a table named day.
The corresponding go struct is the following
type Day struct {
ID string `db:"id" json:"id"`
Dateday string `db:"dateday" json:"dateday"`
Nameday string `db:"nameday" json:"nameday"`
Holyday bool `db:"holyday" json:"holyday"`
}
In an endpoint for Day creation, will be receiving all fields but the ID via a post request
What method should I use to interact with my db so as to:
a) create the record
b) not need to pass the ID myself and instruct postgres to auto-generate the field.
The table creation statement is the following:
CREATE TABLE IF NOT EXISTS "day" (
"id" SERIAL PRIMARY KEY,
"dateday" date NOT NULL,
"nameday" varchar(10) NOT NULL,
"holyday" boolean NOT NULL
);
I would suggest to override the MarshalJSON method as mentioned below:
func (r Day) MarshalJSON() ([]byte, error) {
root := make(map[string]interface{})
root["dateday"] = r.Dateday
root["nameday"] = r.Nameday
root["holyday"] = r.Holyday
return json.Marshal(root)
}
Ref: https://golang.org/pkg/encoding/json/#example__customMarshalJSON
I have a PostgreSQL table
CREATE TABLE reservation_table (
idreservation SERIAL NOT NULL,
entry_datetime TIMESTAMPTZ NOT NULL DEFAULT 'NOW',
start_end_dates DATERANGE NOT NULL ,
property_id INT NOT NULL REFERENCES property_table,
...
)
and a constraint to prevent 2 reservations of the same property on same date
ALTER TABLE ONLY reservation_table
ADD CONSTRAINT reservation_double_booking_constraint
EXCLUDE USING gist
(property_id WITH =, start_end_dates WITH &&)
;
Can I enforce my SQL constraint within my Grails Reservation domain ?
I am considering accessing reservation using a view, to avoid problems with postgresql range in groovy
create view resView as
select idReservation,
lower(start_end_dates) AS startDate,
upper(start_end_dates) AS endDate,
property_id
from reservation_table
Ok , but you specified very minimum information to solve this kind of problem , since i have not understood it fully , i have the following suggestion.
How about using before and after interceptor on grails.
class Reservation {
Date startDate ...
def beforeInterceptor = {
//do some date validation here start data or end date
//for exmaple you might check that we have
//any start date currently existing on db
//by findbyStartDate or endDate
//then reject the reservation or saving of this model
println "validation error here , cancel save"
}
static constraints = {
//do some validation here related to ur constraint
startDate max: new Date()
}
}
let me know anything if u need more help . . .
Hope someone can help me out here as I'm a little stuck.
I'm building a service in front of a hiscore database for a game.
The database have the following two tables:
CREATE TABLE [dbo].[PB_HiscoreEntry] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[PlayerId] UNIQUEIDENTIFIER NOT NULL,
[Score] INT NOT NULL,
[DateCreated] DATETIME NOT NULL
);
CREATE TABLE [dbo].[PB_Player] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[UniquePlayerId] NCHAR (32) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[DateCreated] DATETIME NOT NULL
);
The idea is of course to only have each player once in the database and let them have multiple hiscore entries. This table PB_HiscoreEntry will have a lot of scores, but by doing a simple OrderBy descending, I can create a real hiscore list where the one with highest score is at the top and the lowest at the bottom.
My problem here is that my database don't have any idea of the actual Rank of the score compared to the others. This is something I should do as I do the OrderBy query described above.
Here is some code to help illutrate what I want to archive:
var q = (
from he in entities.PB_HiscoreEntry
orderby he.Score descending
select new HiscoreItem()
{
UserId = he.PB_Player.UniquePlayerId,
Username = he.PB_Player.Name,
Score = he.Score,
//Put in the rank, relative to the other entires here
Rank = 1
});
HiscoreItem, is just my own DTO i need to send over the wire.
So anybody have an idea of how I can do this or am I on a totally wrong path here?
You're on the right track, you just need to use the Queryable.Select overload that takes an extra index. Take a look at this:
var entries =
from entry in entities.PB_HiscoreEntry
orderby entry.Score descending
select entry;
// Note the (entry, index) lambda here.
var hiscores = entries.Select((entry, index) => new HiscoreItem()
{
UserId = entry.PB_Player.UniquePlayerId,
Username = entry.PB_Player.Name,
Score = entry.Score,
Rank = index + 1
});
I'm not 100% sure if Entity Framework knows how to work with the
Select<TSource, TResult>(this IQueryable<TSource>, Expression<Func<TSource, int, TResult>>) overload. If that's the case, just use the equivalent method of the static Enumerable class:
// Note the .AsEnumerable() here.
var hiscores = entries.AsEnumerable()
.Select((entry, index) => new HiscoreItem()
{
UserId = entry.PB_Player.UniquePlayerId,
Username = entry.PB_Player.Name,
Score = entry.Score,
Rank = index + 1
});
I hope this helps.