How to Check Two Conditions in $Criteria->order() in Yii - yii

i have my criteria like the below:
$Criteria = new CDbCriteria();
$Criteria->join='LEFT JOIN abc_tablename ON some_id=one_id';
$Criteria->order = "created_date DESC,commented_date DESC";
the above code sorts only created_date but commented_date is not working... can any one help me in how to order with both the conditions working.

I got the out put by using the following code.
$Criteria->order = " CASE WHEN pc.commented_date IS NULL
THEN t.created_date WHEN pc.commented_date IS NOT NULL THEN
pc.commented_date ELSE 1 END DESC";

Related

Writing SQL statement to select from multiple rows

This might be a silly question to ask. I will appreciate any kind of help.
I'm trying to write a query that count the number of rows based on the logic as below:
count no rows where username = #username and friendsname = #friendsname and username = #friendsname and #friendsname = #username where status = 0
consider the table in the diagram below:
The query should return 1 since id '18' and id '20' have reciprocal values. How will this query be written?
I have written the query as follows which doesn't work:
bool flag = false;
StringBuilder query = new StringBuilder();
query.Append("SELECT Count(id) from friends where username=#username AND friend_username=#friend_username AND username = #friend_username AND friend_username = #username");
query.Append(" AND status=0");
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query.ToString(), con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#username", username));
cmd.Parameters.Add(new SqlParameter("#friend_username", friendusername));
if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
flag = true;
}
}
return flag;
If I'm not mistaken you're trying to count rows given a specific #username and #friendusername that have reciprocal values based on your conditions.
Below query should help, though - I have not tested it in action!
SELECT COUNT(*) as reciprocal_values_no
FROM table_name tbl1
WHERE
username = #username
AND friend_username = #friendusername
AND status = 0
AND EXISTS (
SELECT 1 FROM table_name tbl2 WHERE tbl1.username = tbl2.friend_username AND tbl1.friend_username = tbl2.username )
try this
select username,friend_username,status, count(*)
from table_name
group by username,friend_username,status
having count(*) > 1

How to write correct grammar of sql query statement in asp.net

now I'm facing a problem: I want to get a total number from result='yes' and 'no' from database.
Actually I try a sql query in my sql server studio is working correctly, but when I place the same sql query in the
code of asps.cs, nothing happens, I don't know why. Hope someone can help me to find the problem.
The code as below:
String query_risk1 = "SELECT (SELECT count(result) FROM [rampDB].[dbo].[Answers] WHERE [result]='yes' AND [company] = #deName1 AND [questionID] BETWEEN '1.1a' AND '1.1e' )+(SELECT count(result) FROM [rampDB].[dbo].[Answers] WHERE [result]='no' AND [company] = #deName1 AND [questionID] BETWEEN '1.1a' AND '1.1e')";
DataSet ds_risk = new DataSet();
SqlDataAdapter riskadapter1 = new SqlDataAdapter(query_risk1, sqlConn);
riskadapter1.SelectCommand.Parameters.Add(new SqlParameter("#deName1", site_name));
DataTable risk_table1 = new DataTable();
riskadapter1.Fill(risk_table1);
ds_risk.Tables.Add(risk_table1);
risk_table1 = ds_risk.Tables[0];
grid2.DataSource = ds_risk;
grid2.DataBind();
Try this query
SELECT SUM(CASE WHEN [result] = 'yes' OR [result] = 'no' THEN 1 ELSE 0 END) As Result
FROM [rampDB].[dbo].[answers]
WHERE [company] = #deName1 AND [questionid] BETWEEN '1.1a' AND '1.1e'
May be something like this
String query_risk1 = "SELECT SUM(CASE WHEN [result] = 'yes' OR [result] = 'no' THEN 1 ELSE END) As Result FROM [rampDB].[dbo].[answers] WHERE [company] = #deName1 AND [questionid] BETWEEN '1.1a' AND '1.1e'";
DataSet ds_risk = new DataSet();
SqlDataAdapter riskadapter1 = new SqlDataAdapter(query_risk1, sqlConn);
riskadapter1.SelectCommand.Parameters.Add(new SqlParameter("#deName1", site_name));
DataTable risk_table1 = new DataTable();
riskadapter1.Fill(risk_table1);
ds_risk.Tables.Add(risk_table1);
risk_table1 = ds_risk.Tables[0];
grid2.DataSource = ds_risk;
grid2.DataBind();
your query is similar to this query:
SELECT count(result)
FROM [rampDB].[dbo].[Answers]
WHERE ([result]='yes' OR [result]='no') AND
[company] = #deName1 AND
[questionID] BETWEEN '1.1a' AND '1.1e'
and finally if you use this query you can tru ExecuteScaler() method to get return value of query:
SqlConnection sqlCon = new SqlConnection("YOUR SQL CONNECTIONSTRING");
SqlCommand sqlCom = new SqlCommand("THE QUERY", sqlCon);
sqlCom.Parameters.AddWithValue("#deName1", "SOME VALUE");
sqlCon.Open();
int count = (int)sqlCom.ExecuteScaler();
sqlCon.Close();

Entity Framework query with "not in"

I have a simple (well easy, not simple) query of "not in" on related tables.
SELECT CompetencyID, CompetencyName FROM Competency
WHERE (Deleted = 0) AND (CompanyID = 1) AND (CompetencyID NOT IN(SELECT CompetencyID
FROM CompetencyGroups WHERE (Deleted = 0) AND (CompanyID = 1) AND (GroupID = 1))) AND
(ParentID = 0) ORDER BY CompetencyName
In SQL I get the list that I need with remaining items not in the group. Now I want to bind this to a DataGrid using EF5.
I cannot get the query syntax properly (Using VB.net) to list the ID and the Name of the Competency...
Converted the provided c# answer to VB:
Dim excludeList = context.CompetencyGroups.Where(Function(x) x.Deleted = False And x.GroupID = GroupID).Select(Function(x) x.CompetencyID).ToArray
Dim results = context.Competencies.Where(Function(c) Not excludeList.Contains(c.CompetencyID) And c.Deleted = False And c.CompanyID = 1 And c.ParentID = 0).OrderBy(Function(c) c.CompetencyName)
GridView2.DataSource = results
GridView2.DataBind()
Hope this helps someone in the future. Took me about 4 hours to search, ask and convert...
Something like
var excludeList = context.CompetencyGroups.Where(x => x....).Select(x => x.CompetencyID).ToArray();
var results = context.Competency.Where(x => !excludeList.Contains(x.CompetencyID));
Update: Somebody else edited this and then someone rejected it, but the edit was a good one (to select the value)
If you need the Cast to make an array of Integers.
Dim excludeList = context.CompetencyGroups.Cast(Of CompentencyGroup).Select(Function(x) x.CompetencyID).ToArray()
Dim results = context.Competency.Where(Function(x) Not excludeList.Contains(x.CompetencyID))

Where clause on dynamic column name in LINQ query?

I've created a dropdown with some column names in a table in my db. When a user selects a column name i want to add a where clause to the query to use this filter.
What i'm trying to do is:
Dim objQuery = (From wc In _dbBellen.dealer_telefonies Order By wc.Bedrijfsnaam Select wc)
'if dropdown has value...
objQuery = objQuery.Where(Function(wc) wc.DynamicColumnName < txtFilterValue1.Text)
The wc.DynamicColumnName has to be replaced by for example wc.Price.
--
The code what i'm tried now after some replies is:
Dim objQuery = (From wc In _dbBellen.dealer_telefonies Order By wc.Bedrijfsnaam Select wc)
If ddlFilterColumn1.SelectedValue <> "" And ddlFilterOperator1.SelectedValue <> "" And txtFilterValue1.Text <> "" Then
Select Case ddlFilterOperator1.SelectedValue
Case "..%"
objQuery = objQuery.Where(Function(wc) wc.WHMCSClient_id Like txtFilterValue1.Text & "%")
Case "%.."
objQuery = objQuery.Where(Function(wc) wc.WHMCSClient_id Like "%" & txtFilterValue1.Text)
Case Else '< > = <>
'objQuery = objQuery.Where(Function(wc) wc.WHMCSClient_id < txtFilterValue1.Text)
'objQuery = objQuery.Where(Function(wc) "wc." + ddlFilterColumn1.SelectedValue.ToString + " < " + txtFilterValue1.Text)
objQuery = objQuery.Where(Function(wc) "wc.WHMCSClient_id < 500")
End Select
End If
Response.Write(objQuery.ToString())
But i am getting the following error (original error is in dutch but it said as follow):
The conversion from string wc.WHMCSClient_id < 500 to type Boolean is invalid.
This is quite an old article, but I think it's still viable
Scott Gu posted about the Dynamic LINQ library a while back which essentially allows you to use strings to query collections in a "LINQ"-type format., i.e. something like this:
Dim objQuery = (From wc In _dbBellen.dealer_telefonies Order By wc.Bedrijfsnaam Select wc)
// if dropdown has value...
Dim result = objQuery.Where("MyColumnName < " + txtFilterValue1.Text);
Here's a link to the full article: Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)

Linq query returning value from another class

Just a quick question about LINQ, I want to use a value from the returned dataset to lookup a value and return this. The line I am struggling with is .ViewingNotes = New Viewing(pt.ProspectId).GetViewings().Columns(7).ToString(). Is this possible?
With BusinessLayerObjectManager.Context
Return (From p As [Property] In .PropertySet
Join pt As Prospect In .Prospects On pt.Property.propertyID Equals p.propertyID
Where (p.Development.DevelopmentID = devId)
Select New DevelopmentList With {
.Apartment = p.propertyApartment + " " + p.Development.Name,
.PropertyId = p.propertyID,
.Client = pt.Client.clientFirstname + " " + pt.Client.clientLastname,
.ClientId = pt.Client.ClientID,
.ProspectiveDate = pt.prospectiveDate,
.ProspectiveStatus = pt.prospectiveStatus,
.Agent = pt.Client.userID,
.ViewingNotes = New Viewing(pt.ProspectId).GetViewings().Columns(7).ToString(),
.PropertyStatus = ""
}).ToList()
End With
Thanks in advance.
I suspect not, when the compiler tries to convert the 'Viewing(pt.ProspectId).GetViewings().Columns(7).ToString()' bit to SQL it will get very confused. You would need to do it in 2 stages.
Do the first Linq-to-entity select first returning just pt.ProspectId, with the .ToList() intact. Then use the results to do some more linq, linq-to-linq if you like, where you can do the lookup using a lambda.