how to query objects lookup relationship and count records? - soql

I have an custom Invoice object with a look-up relationship to Accounts.
I'm trying to query the data base to get the total number of invoices of the accounts where Connection_Date__c has a value (Connection_Date__c is a custom field of Accounts object)
How can I do this? The query I'm using gives me only the number of accounts but not the number of invoices.
SELECT Name,(SELECT name FROM Invoices__r) FROM Account WHERE Connection_Date__c != null

In SOQL, it's almost easier to write queries that are driven from the child rather than the parent. This is opposite of SQL
Try a query that matches this pattern:
SELECT Count() FROM ChildTable WHERE ChildTable.parentField != Null

SELECT (Parent_Api_Name_In_Child_Object),
COUNT(ID)
(Child_Realtionship_Name__r.Parent_Fields....)
FROM (Child_Object_Api_Name)
GROUP BY (Parent_Api_Name_Child_Object,
Parent Feilds with API Names)
HAVING COUNT(ID){>,<,=,{Optional}}
it is an SQL queried answer
Let me know in case of any questions

Related

BigQuery - Crashlytics : find all users affected by all issues

Taking account that to retrieve all users affected by a particular issue, we have to write this query :
SELECT user.id as user_id
FROM
`projectId.firebase_crashlytics.package_name_ANDROID`
WHERE
issue_id = "YOUR_ISSUE_ID"
AND application.display_version = ""
AND user.id != ""
ORDER BY
user.id;
As stated here in the 6th example : https://firebase.google.com/docs/crashlytics/bigquery-export#examples_of_crashlytics_queries
Which query does retrieve all the users affected by all issues?
If you wanted to find all the IDs for users affected by any issue - you can write a query like this:
SELECT distinct user.id as user_id
FROM
`projectId.firebase_crashlytics.package_name_ANDROID`
You can remove the filters (WHERE clauses) because you want to consider all issues. The DISTINCT clause will remove any duplicates and simply give you one record for each user

Cosmos db Order by on 'computed field'

I am trying to select data based on a status which is a string. What I want is that status 'draft' comes first, so I tried this:
SELECT *
FROM c
ORDER BY c.status = "draft" ? 0:1
I get an error:
Unsupported ORDER BY clause. ORDER BY item expression could not be mapped to a document path
I checked Microsoft site and I see this:
The ORDER BY clause requires that the indexing policy include an index for the fields being sorted. The Azure Cosmos DB query runtime supports sorting against a property name and not against computed properties.
Which I guess makes what I want to do impossible with queries... How could I achieve this? Using a stored procedure?
Edit:
About stored procedure: actually, I am just thinking about this, that would mean, I need to retrieve all data before ordering, that would be bad as I take max 100 value from my database... IS there any way I can do it so I don t have to retrieve all data first? Thanks
Thanks!
ORDER BY item expression could not be mapped to a document path.
Basically, we are told we can only sort with properties of document, not derived values. c.status = "draft" ? 0:1 is derived value.
My idea:
Two parts of query sql: The first one select c.* from c where c.status ='draft',second one select c.* from c where c.status <> 'draft' order by c.status. Finally, combine them.
Or you could try to use stored procedure you mentioned in your question to process the data from the result of select * from c order by c.status. Put draft data in front of others by if-else condition.

Whats the best way to query DynamoDB based on date range?

As part of migrating from SQL to DynamoDB I am trying to create a DynamoDB table. The UI allows users to search based on 4 attributes start date, end date, name of event and source of event.
The table has 6 attributes and the above four are subset of it with other attributes being priority and location. The query as described above makes it mandatory to search based on the above four values. whats the best way to store the information in DynamoDB that will help me in querying based on start date and end date fairly easy.
I thought of creating a GSI with hashkey as startdate, rangekey as end date and GSI on the rest two attributes ?
Inshort:
My table in DynamoDB will have 6 attributes
EventName, Location, StartDate, EndDate, Priority and source.
Query will have 4 mandatory attributes
StartDate, EndDate, Source and Event Name.
Thanks for the help.
You can use greater than/less than comparison operators as part of your query http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html
So you could try to build a table with schema:
(EventName (hashKey), "StartDate-EndDate" (sortKey), other attributes)
In this case the sort-key is basically a combination of start and end date allowing you to use >= (on the first part) and <= (on the second part)... dynamodb uses ASCII based alphabetical ordering... so lets assume your sortKey looks like the following: "73644-75223" you could use >= "73000-" AND <= "73000-76000" to get the given event.
Additionally, you could create a GSI on your table for each of your remaining attributes that need to be read via query. You then could project data into your index that you want to fetch with the query. In contrast to LSI, queries from GSI do not fetch attributes that are not projected. Be aware of the additional costs (read/write) involved by using GSI (and LSI)... and the additional memory required by data projections...
Hope it helps.

SQLite: SELECT from grouped and ordered result

I'm new to SQL(ite), so i'm sorry if there is a simple answer i just were to stupid to find the right search terms for.
I got 2 tables: 1 for user information and another holding points a user achieved. It's a simple one to many relation (a user can achieve points multiple times).
table1 contains "userID" and "Username" ...
table2 contains "userID" and "Amount" ...
Now i wanted to get a highscore rank for a given username.
To get the highscore i did:
SELECT Username, SUM(Amount) AS total FROM table2 JOIN table1 USING (userID) GROUP BY Username ORDER BY total DESC
How could i select a single Username and get its position from the grouped and ordered result? I have no idea how a subselect would've to look like for my goal. Is it even possible in a single query?
You cannot calculate the position of the user without referencing the other data. SQLite does not have a ranking function which would be ideal for your user case, nor does it have a row number feature that would serve as an acceptable substitute.
I suppose the closest you could get would be to drop this data into a temp table that has an incrementing ID, but I think you'd get very messy there.
It's best to handle this within the application. Get all the users and calculate rank. Cache individual user results as necessary.
Without knowing anything more about the operating context of the app/DB it's hard to provide a more specific recommendation.
For a specific user, this query gets the total amount:
SELECT SUM(Amount)
FROM Table2
WHERE userID = ?
You have to count how many other users have a higher amount than that single user:
SELECT COUNT(*)
FROM table1
WHERE (SELECT SUM(Amount)
FROM Table2
WHERE userID = table1.userID)
>=
(SELECT SUM(Amount)
FROM Table2
WHERE userID = ?);

how to make left join between two tables without relation in doctrine 1.2

I have two tables.
Table invitations
Columns:
id email created_at
Table orders
Columns:
id amount email created_at
i need to create a DQL to select all the fields from invitations table and left join with count of all the record in orders table with on email
NOTE I need to view the results so I need to paginate the results and there is no relation between the two tables
Create the DQL query:
$q = Doctrine_Query::create()
->select('i.*')
->from('invitations i')
->leftJoin('i.orders o ON i.email=o.email')
;
You may add more conditions:
->having('COUNT(email) > 10')
->groupBy('i.email')
->orderBy('i.email ASC');
Print the result SQL query to check for errors:
echo $q->getSqlQuery();
Execute the DQL query:
$vrows = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); //For speed use Hydrate_Array, read the documentation about hydrating methods. If not specified you will get a list of records objects.
Another way would be like ilSavo and Michal said, create your own query or write in your schema the relation between those two tables.
A third way would be to directly send the SQL raw query to the database, without using the ORM Doctrine:
$oConnection = Doctrine_Manager::getInstance()->getConnectionForComponent($sModuleName);
$vrecords = $oCurrentConnection->fetchAssoc($sSQLquery);
In order to paginate your results take a look here.
Remember to use try and catch in order to get exceptions.

Resources