How to sort Microsoft Azure database table data BY DATE - sql

I am trying to sort the rows in my table by the latest date first.
var userParkingHistory = from j in dataGateway.SelectAll() select j ;
userParkingHistory = userParkingHistory.Where(ParkingHistory => ParkingHistory.username == User.Identity.Name);
return View(userParkingHistory);
I can currently display the rows sorted by the username but I also want it to sort by the latest date first.
In my gateway, this is how I select the list:
public IEnumerable<T> SelectAll()
{
return data.ToList();
}
Where and How do I sort the data according to the latest date first ?
This is how I define my table:
CREATE TABLE [dbo].[ParkingHistory] (
[parkingHistoryId] INT IDENTITY (1, 1) NOT NULL,
[carparkId] INT NULL,
[username] VARCHAR (255) NULL,
[date] DATETIME NULL,
[description] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([parkingHistoryId] ASC)
);

Linq has orderby:
var userParkingHistory = from j orderby j.date in dataGateway.SelectAll() select j ;
Alsi, List has various extension methods to sort itself.

Try this:
var userParkingHistory = dataGateway.SelectAll().Where(p => p.username == User.Identity.Name).OrderBy(p => p.date).ToList();
return View(userParkingHistory);

Related

Dealing with collections in SQL

I have this table in which I want to register likes from users. The data type for likes is an array. INT[] I don't know if this is the best approach to handle like and unlike
I have not found an effective way to manipulate collection in order to toggle like/unlike from a user.
can we use sthg like an associative array in SQL? or, what would be the best approach with an array ? I could not find one example.
Thks for pointing me in the right direc†ion.
CREATE TABLE posts (
pid SERIAL PRIMARY KEY,
user_id INT REFERENCES users(uid),
author VARCHAR REFERENCES users(username),
title VARCHAR(255),
content TEXT,
date_created TIMESTAMP,
like_user_id INT[] DEFAULT ARRAY[]::INT[],
likes INT DEFAULT 0
);
const likePost = (req, res, next) => {
const values = [req.body.id, req.body.user_id];
console.log(values);
const query = `UPDATE posts SET likes = likes - 1 WHERE pid = $1, UPDATE posts SET likes[1] = $2 WHERE pid = $1`;
pool.query(query, values, (q_err, q_res) => {
if (q_err) return next(q_err);
res.json(`post ${req.body.id} succcessfully remove 👍`);
});
};

PhoneGap sql checking for duplicates

I want to input a query to check the database for duplicate when inserting data into the database so it would prevent the activity Name from being entered more than once in a database
function insertQueryDB(tx) {
var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
var an = document.forms["myForm"]["activityName"].value;
var l = document.forms["myForm"]["location"].value;
var t = document.forms["myForm"]["time"].value;
var d = document.forms["myForm"]["date"].value;
var r = document.forms["myForm"]["reporter"].value;
var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);
tx.executeSql(query,[]);
}``
Create the table with name being unique:
CREATE TABLE IF NOT EXISTS dataEntryTb (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
activityName TEXT NOT NULL UNIQUE,
location TEXT NOT NULL,
time NOT NULL, date NOT NULL,
reporter NOT NULL
);
Then the database will return an error if the name is already in the table.

Fluent NHibernate QueryOver fails on subquery

I have a table that has datetime field and nvarchar field. I am trying to do a query that fetches only newest rows for each nvarchar field using Fluent Nhibernate QueryOver.
Table is here:
CREATE TABLE [dbo].[DataItem] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Source] NVARCHAR (50) NULL,
[Target] NVARCHAR (50) NULL,
[SendDateTime] DATETIME NULL,
[Version] INT NULL
);
QueryOver code is here:
DataItem dataItemAlias = null;
var c = QueryOver.Of<DataItem>(() => dataItemAlias);
c.WhereRestrictionOn(x => x.Source).IsInsensitiveLike("A");
DataItem maxSendDateTimeAlias = null;
var subQuery = QueryOver.Of<DataItem>(() => maxSendDateTimeAlias)
.Select(Projections.ProjectionList()
.Add(Projections.Max(() => maxSendDateTimeAlias.SendDateTime))
.Add(Projections.Group(() => maxSendDateTimeAlias.Target)))
.Where(() => dataItemAlias.Source == maxSendDateTimeAlias.Source);
c.WithSubquery.WhereProperty(p => p.SendDateTime).In(subQuery);
var result = c.GetExecutableQueryOver(Session).List<DataItem>();
This is the SQL query:
SELECT this_.ID as ID0_0_, this_.Source as Source0_0_, this_.Target as Target0_0_, this_.SendDateTime as SendDate4_0_0_, this_.Version as Version0_0_ FROM [DataItem] this_
WHERE lower(this_.Source) like 'a' and this_.SendDateTime in (SELECT max(this_0_.SendDateTime) as y0_, this_0_.Target as y1_
FROM [DataItem] this_0_ WHERE this_.Source = this_0_.Source GROUP BY this_0_.Target)
If I remove the
this_0_.Target as y1_
from
SELECT max(this_0_.SendDateTime) as y0_, this_0_.Target as y1_
FROM [DataItem] this_0_...
It is correct query and I get the correct results.
This is the error I get:
"Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS."
Here are the sources
So yeah the bug is real and here is a workaround
var subQuery =
QueryOver.Of<DataItem>()
.Select(
Projections.ProjectionList()
.Add(Projections.SqlGroupProjection("max(SendDateTime) as maxSendDateTimeAlias", "Target",
new string[] { "maxAlias" }, new IType[] { NHibernate.NHibernateUtil.Int32 })));
Got the answer from this post

Hibernate 3.4.0: How to query for a scalar value

I have: (MySQL 5.1)
CREATE TABLE `poh_faktury` (
`cislo` int(10) unsigned NOT NULL PRIMARY KEY,
...
) ENGINE=MyISAM DEFAULT CHARSET=utf8$$
#Entity
#Table(name="poh_faktury")
#NamedQueries({
#NamedQuery(name="dalsiCisloFaktury", query="SELECT MAX(fakt.cislo) + 1 FROM Faktura AS fakt")
})
The generated queries (yes, two) are:
select MAX(faktura0_.cislo)+1 as col_0_0_ from poh_faktury faktura0_
select MAX(faktura0_.cislo)+1 as col_0_0_ from poh_faktury faktura0_ limit 2
But this
Integer res = ((Integer) this.getJpaTemplate().execute( new JpaCallback() {
public Object doInJpa( EntityManager em ) throws PersistenceException {
Query q = em.createNamedQuery( "dalsiCisloFaktury" );
return q.getSingleResult();
}
}));
puts null into res.
When I invoke SQL, it returns 1000 as it should:
SELECT MAX(fakt.cislo) + 1 FROM poh_faktury AS fakt;
How should I make Hibernate return correct scalar value?

How To Split Pipe-Delimited Column and insert each value into new table Once?

I have an old database with a gazillion records (more or less) that have a single tags column (with tags being pipe-delimited) that looks like so:
Breakfast
Breakfast|Brunch|Buffet|Burger|Cakes|Crepes|Deli|Dessert|Dim Sum|Fast Food|Fine Wine|Spirits|Kebab|Noodles|Organic|Pizza|Salad|Seafood|Steakhouse|Sushi|Tapas|Vegetarian
Breakfast|Brunch|Buffet|Burger|Deli|Dessert|Fast Food|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
Breakfast|Brunch|Buffet|Cakes|Crepes|Dessert|Fine Wine|Spirits|Salad|Seafood|Steakhouse|Tapas|Teahouse
Breakfast|Brunch|Burger|Crepes|Salad
Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Vegetarian
Breakfast|Brunch|Deli|Dessert|Organic|Salad
Breakfast|Brunch|Dessert|Dim Sum|Hot Pot|Seafood
Breakfast|Brunch|Dessert|Dim Sum|Seafood
Breakfast|Brunch|Dessert|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood
Breakfast|Brunch|Dessert|Fine Wine|Spirits|Salad|Vegetarian
Is there a way one could retrieve each tag and insert it into a new table tag_id | tag_nm using MySQL only?
Here is my attempt which uses PHP..., I imagine this could be more efficient with a clever MySQL query. I've placed the relationship part of it there too. There's no escaping and error checking.
$rs = mysql_query('SELECT `venue_id`, `tag` FROM `venue` AS a');
while ($row = mysql_fetch_array($rs)) {
$tag_array = explode('|',$row['tag']);
$venueid = $row['venue_id'];
foreach ($tag_array as $tag) {
$rs2 = mysql_query("SELECT `tag_id` FROM `tag` WHERE tag_nm = '$tag'");
$tagid = 0;
while ($row2 = mysql_fetch_array($rs2)) $tagid = $row2['tag_id'];
if (!$tagid) {
mysql_execute("INSERT INTO `tag` (`tag_nm`) VALUES ('$tag')");
$tagid = mysql_insert_id;
}
mysql_execute("INSERT INTO `venue_tag_rel` (`venue_id`, `tag_id`) VALUES ($venueid, $tagid)");
}
}
After finding there is no official split function I've solved the issue using only MySQL like so:
1: I created the function strSplit
CREATE FUNCTION strSplit(x varchar(21845), delim varchar(255), pos int) returns varchar(255)
return replace(
replace(
substring_index(x, delim, pos),
substring_index(x, delim, pos - 1),
''
),
delim,
''
);
Second I inserted the new tags into my new table (real names and collumns changed, to keep it simple)
INSERT IGNORE INTO tag (SELECT null, strSplit(`Tag`,'|',1) AS T FROM `old_venue` GROUP BY T)
Rinse and repeat increasing the pos by one for each collumn (in this case I had a maximum of 8 seperators)
Third to get the relationship
INSERT INTO `venue_tag_rel`
(Select a.`venue_id`, b.`tag_id` from `old_venue` a, `tag` b
WHERE
(
a.`Tag` LIKE CONCAT('%|',b.`tag_nm`)
OR a.`Tag` LIKE CONCAT(b.`tag_nm`,'|%')
OR a.`Tag` LIKE CONCAT(CONCAT('%|',b.`tag_nm`),'|%')
OR a.`Tag` LIKE b.`tag_nm`
)
)