SQLKata - Nested queries - How can i write the code for my query in using sqlkata for sqlserver in c#? - sqlkata

How can i write the code for the below query in using sqlkata for sqlserver in c#?
SELECT [t0].Region
FROM ((select * from [dbo].Demo_ReportData )) AS [t0]
GROUP BY [t0].Region
ORDER BY [t0].Region ASC
offset 0 rows fetch next 50 rows only;

To use the offset fetch syntax you have to set the UseLegacyPagination to false on the SqlServerCompiler.
var compiler = new SqlServerCompiler { UseLegacyPagination = false };
var innerQuery = new Query("Demo_ReportData");
var query = new Query().From(innerQuery.As("t0"))
.GroupBy("Region")
.OrderBy("Region")
.Take(50);
var result = compiler.Compile(query);
var sql = result.Sql;
var bindings = result.Bindings;

Related

How can use BETWEEN in sqlite via db.query

I've a query on sqlite that use "between" and I want to use it on standard Query.
my code is here:
String[] columns = new String[]{"_id", "question_group", "question_number", "is_answered"};
String selection = "question_group = ?";
String[] selectionArgs = new String[]{String.valueOf(category)};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.query(TABLE_QUESTION, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
I want to Add another condition that is :question_number between 1 and 10. I can now write this query in a single statement but I want to use it as above I told.
From the Android documentation describing the selection parameter of the query() method:
A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
If you want the following WHERE clause in your query
WHERE question_group = :category AND question_number BETWEEN 1 AND 10
then you can use the following selection and selectionArgs:
String selection = "question_group = ? AND question_number BETWEEN ? AND ?";
String[] selectionArgs = new String[]{ String.valueOf(category), "1", "10"};

How to write the HAVING clause with SQL COUNT(DISTINCT column_name) function in Codeigniter Active Record?

I am using Codeigniter and am trying to use the Active Record Class for all my database operations.
However, I did run into problems when trying to convert the last bid of the following (working) query into Active Record code.
$sql = ("SELECT ac.cou_id
FROM authorcourse ac
INNER JOIN course c
ON ac.cou_id = c.cou_id
WHERE cou_name = ? // ? = $cou_name
AND cou_number = ? // ? = $cou_number
AND cou_term = ? // ? = $cou_term
AND cou_year = ? // ? = $cou_year
AND FIND_IN_SET (ac.aut_id, ?) //? = $aut_ids_string
GROUP BY ac.cou_id
HAVING COUNT(DISTINCT ac.aut_id) = ? //? = $aut_quantity
AND COUNT(DISTINCT ac.aut_id) = (SELECT COUNT(DISTINCT ac2.aut_id)
FROM authorcourse ac2
WHERE ac2.cou_id = ac.cou_id)");
$query = $this->db->query($sql, array($cou_name, $cou_number, $cou_term, $cou_year, $aut_ids_string, $aut_quantity));
Question: How do I convert the HAVING clause into valid Active Record code?
I tried using $this->db->having(); and $this->db->distinct(); but failed to combine the functions to achieve the desired result.
My (working) code so far:
$this->db->select('ac.cou_id');
$this->db->from('authorcourse ac');
$this->db->join('course c', 'c.cou_id = ac.cou_id');
$this->db->where('cou_name', $cou_name);
$this->db->where('cou_number', $cou_number);
$this->db->where('cou_term', $cou_term);
$this->db->where('cou_year', $cou_year);
$this->db->where_in('ac.aut_id',$aut_ids);
$this->db->group_by('ac.cou_id');
// missing code
Thanks a lot!
You code seems quite clumsy. But, you can use having clause in the following way:
$this->db->having("ac.aut_id = '".$aut_qty."'", null, false)

how to get the second batch and 3rd batch in the same query result in oracle sql + yii framework?

let' say i have 20 results in the sql query. if am gonna use the limit in the yii active record, I'll obviously get the first four from the result, but what if i wanna get the 2nd four and then 3rd four in the same query result ? how to query that via sql ?
e.g
$criteria2 = new CDbCriteria();
$criteria2->select = 'USERID, ADID ,ADTYPE, ADTITLE, ADDESC, PAGEVIEW, DISPPUBLISHDATE';
$criteria2->addCondition("STATUS = 1");
$criteria2->order = '"t".PAGEVIEW DESC,"t".PUBLISHDATE DESC';
$criteria2->limit = 4;
$criteria2->with = array('subcat','adimages');
$result = $this->findAll($criteria2);
return $result;
Sorry :)
See here, how to paginate with Oracle (Are you use 11g?)
Alternatives to LIMIT and OFFSET for paging in Oracle
Well and in Yii just set offset, OCIConnector will set rownum automaticly for sql
$criteria2 = new CDbCriteria();
$criteria2->select = 'USERID, ADID ,ADTYPE, ADTITLE, ADDESC, PAGEVIEW, DISPPUBLISHDATE';
$criteria2->addCondition("STATUS = 1");
$criteria2->order = '"t".PAGEVIEW DESC,"t".PUBLISHDATE DESC';
$criteria2->limit = 4;
$criteria2->offset = 0; //4, 8 - COciCommandBuiled applyLimit use it
$criteria2->with = array('subcat','adimages');
$result = $this->findAll($criteria2);
return $result;

SQL date comparison in WHERE clause, TypoScript

I want to compare dates in a TypoScript select.
Here's what I have (note that I commented the were clauses) :
lib.my_val = CONTENT
lib.my_val {
select {
pidInList = 100000
max = 1
#where = effective_date < CURDATE()
#where = TIMESTAMP(effective_date) < NOW()
orderBy = effective_date DESC
}
table = tx_my_table
renderObj = COA
renderObj {
5 = TEXT
5{
field = my_field
wrap = <span>|</span>
}
[...]
}
}
Which returns lines.
I tried to add a where statement any way I could with static dates or variables... without success. My understanding of the where clause is that everything after the = is dumped as is in the SQL query. But it seems I missed something.
Basically I want the TypoScript to generate a SQL Query smilar to this :
SELECT * FROM tx_my_table WHERE effective_date < NOW() ORDER BY effective_date DESC LIMIT 1;
This should be simple. Has anyone done this in the past?
Thanks!
Your TypoScript seems to be OK.
What happens if you enter the SQL Query directly into MySQL?
Note that with your code, only one record with pid=100000 is
selected.
Have you tried this:
--
lib.my_val {
select {
pidInList = 100000
max = 1
where = UNIX_TIMESTAMP(effective_date) < UNIX_TIMESTAMP()
orderBy = UNIX_TIMESTAMP(effective_date) DESC
}
table = tx_my_table
}
TYPO3 Wiki on select

NHibernate query count

I am new to NHibernate and I want to have a count of rows from database. Below is my code,
SearchTemplate template = new SearchTemplate();
template.Criteria = DetachedCriteria.For(typeof(hotel));
template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
template.Criteria.Add(Restrictions.Eq("Canceled", "False"));
int count = template.Criteria.SetProjection(Projections.Count("ID"));
It gives me an error when I try to compile app that says
"Cannot implicitly convert type 'NHibernate.Criterion.DetachedCriteria' to 'int'"
I want to have a count of rows of the table hotel..
You want to use GetExecutableCriteria:
SearchTemplate template = new SearchTemplate();
template.Criteria = DetachedCriteria.For(typeof(hotel));
template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
template.Criteria.Add(Restrictions.Eq("Canceled", "False"));
var count = DoCount(template.Criteria, session /* your session */);
public long DoCount(DetachedCriteria criteria, ISession session)
{
return Convert.ToInt64(criteria.GetExecutableCriteria(session)
.SetProjection(Projections.RowCountInt64())
.UniqueResult());
}
On a side note, you should take a look at using NHibernate.Linq:
var result = (from h in Session.Linq<Hotel>()
where h.CheckOutDate <= SelDate
where h.Canceled != true
select h).Count();
More information here.