Reduce arrays where values are equals - arrays

It's a simple question I think, but i can't handle this.
If you see the image, here is my DB with multiple Usernames and "instances_id". If I var_dump this I have 11 arrays (and that's normal).
Is there a way to reduce arrays where "instance_id" is equal?
So that I have the first array containing "Alessio,Giorgio", the second one "Alessio,Giovanni" etc.
I use laravel... I hope you can help me

You could use combination of GROUP BY with GROUP_CONCAT to retrieve directly from db:
$result = DB
::table('example')
->selectRaw('instance_id, GROUP_CONCAT(Username)')
->groupBy('instance_id')
->get();
Or via laravel collection:
$result = DB::table('example')->get();
$result = $result
->groupBy('instance_id')
->map(function($group){
$data = $group->first();
$data->Username = $group->pluck('Username')->implode(',');
return $data;
})
->values();

Try..
SELECT * FROM tableName GROUP BY fieldName;
The following query will select all fields along with distinct zip field.

There are two ways.
1)select *
from table
group by field1
2) select distinct on field1 *
from table

Related

CAKEPHP 3 : Select * and sum() in one statement

I am trying to fetch result from database table with SELECT * and SUM() function.
The sql query is :
SELECT * ,SUM(msg_send) AS msg_send FROM msg_campaigns
Now how to write this query in cakephp3.
I am trying this :
$this->loadModel('MsgCampaigns');
$SmsDetails = $this->MsgCampaigns->find('all',[
'conditions'=>['YEAR(date_time)'=>date('Y')],
'fields'=>['msg_send'=>'SUM(msg_send)','msg_failed'=>'SUM(msg_failed)']
]);
But I do not know how to use SELECT * . Please help
Check the CakePHP Query Builder on how to use SQL functions and how to select all fields.
$query = $this->MsgCampaigns->find();
$query
->select([
'sum_msg_send' => $query->func()->sum('msg_send'),
'sum_msg_failed' => $query->func()->sum('msg_failed')
])
// passing the table instance to the `select` function, selects all fields
->select($this->MsgCampaigns);
$query->execute();

U-SQL cursor in Azure Data Lake

I need to process data in Azure Data Lake.
My flow is as follows:
I would like to select from the database list of IDs for next processing. This I have done.
I need to iterate through IDs (from the first step) and I need to successively export data into separated files (partitioned by ID)
The problem is following statemanet:
U-SQL’s procedures do not provide any imperative code-flow constructs
such as a for or while loops.
Any idea how to process data in similar way as with cursor?
I didn't find any documentation regarding to the cursors in U-SQL.
Thank you!
There are no cursors in U-SQL, because of the statement you reference above.
U-SQL does not provide any imperative code-flow constructs because it impedes the optimizer's ability to globally optimize your script.
You should think of approaching your problem declaratively. For example, if you have a list of IDs (either in a table or SqlArray or even a file), use a declarative join. For example, you want to add 42 to every value where the key is in a list of existing keys:
// Two options for providing the "looping data"
// Option 1: Array Variable
DECLARE #keys_var = new SqlArray<string>{"k1", "k2", "k3"};
// Option 2: Rowset (eg from an EXTRACT from file, a table or other place)
#keys = SELECT * FROM (VALUES("k1"), ("k2"), ("k3")) AS T(key);
// This is the data you want to iterate over to add 42 to the value column for every matching key
#inputdata = SELECT * FROM (VALUES (1, "k1"), (2, "k1"), (3, "k2"), (6, "k5")) AS T(value, key);
//Option 1:
#res = SELECT value+42 AS newval, key FROM #inputdata WHERE #keys_var.Contains(key);
OUTPUT #res TO "/output/opt1.csv" USING Outputters.Csv();
//Option 2:
#res = SELECT value+42 AS newval, i.key
FROM #inputdata AS i INNER JOIN #keys AS k
ON i.key == k.key;
OUTPUT #res TO "/output/opt2.csv" USING Outputters.Csv();
Now in your case, you want to have data-driven output file sets. This feature is currently being worked on (it is one of our top asks). Until then you would have to write a script to generate the script (I will provide an example on your other question).
If you really want iterative behaviour you need to call the USQL from PowerShell.
For example:
ForEach ($Date in $Dates)
{
$USQLProcCall = '[dbo].[usp_OutputDailyAvgSpeed]("' + $Date + '");'
$JobName = 'Output daily avg dataset for ' + $Date
Write-Host $USQLProcCall
$job = Submit-AzureRmDataLakeAnalyticsJob `
-Name $JobName `
-AccountName $DLAnalyticsName `
–Script $USQLProcCall `
-DegreeOfParallelism $DLAnalyticsDoP
Write-Host "Job submitted for " $Date
}
Source: https://www.purplefrogsystems.com/paul/2017/05/recursive-u-sql-with-powershell-u-sql-looping/

how to get approximate searching results in sql server 2014

How to write sql procedure to get matching results while searching for string values.It should search by the similarity of the characters entered by user. For instance Ahmmed, Ahmad, Ahmmad or Mohammad, Mohammed, Mohamad etc should display all similar names while executing search.
Any help would be highly appreciated.
Thanks in advance.
Well I guess you need AI for that but, you can use the like keyword to do wildcards.
e.g.
$search_string = 'Ahm'; //or Moha
$query = SELECT column FROM tableName WHERE column LIKE '$search_string%'; //starts with the $search_string
or
$query = SELECT column FROM tableName WHERE column LIKE '%$search_string'; //ends with the $search_string
or
$query = SELECT column FROM tableName WHERE column LIKE '%$search_string%'; //starts and/or ends with the $search_string
take note of the %

How to select columns with other name in linq?

I select my records in SQL Server Query as you seen below:
SELECT ProductName 'Some Name1' ,
Payment 'Some Name2'
FROM dbo.PrefactorProduct
Is there a way to select records like that in linq queries?
You can project result from your query to an Anonymous type and use different alias/field names for your fields.
var query = db.PrefactorProduct
.Select(r=> new
{
SomeName1 = r.ProductName,
SomeName2 = r.Payment
});
But if you are trying to format your result set for displaying purpose then you should look in to assigning column names for your grid/ data container.

how to use "find_in_set" in cakephp find method

I have a table in which comma seprated id of another table i want to use the following query in cakephp in proper form with find function
"select * from special_offers where find_in_set('".$storeId."', stores) and user_id = '". $userId ."'";
Use like this
$data = $this->SpecialOffer->find('all',array('conditions' => array('SpecialOffer.user_id' => $userId ,'FIND_IN_SET(\''. $storeId .'\',SpecialOffer.stores1)')));
Hope this may help you

Resources