SQL group dates as week date - sql

I have a table which contains func_id and date in format like (07.06.14 ). I am trying to create a function that returns the number of dates that is the week day of a date (07.06.14 ) and the func_id will equals the func_id that I will write. For example:
My table:
func_id 11 / date = 07.06.14
That will return 1 from 0. (Saturday code = 0);
I tried:
function Get_weekday($data){
$dat = explode(".",$data);
$date = date("l", mktime(0, 0, 0, $dat[0] , $dat[1], $dat[2]));
if($date == "Monday"){return 4;}
if($date == "Tuesday"){return 3;}
if($date == "Wednesday"){return 2;}
if($date == "Thursday"){return 1;}
if($date == "Friday"){return 0;}
if($date == "Saturday"){return 0;}
if($date == "Sunday"){return 0;}
}
function count_per_date($func_id,$day){
$result = mysql_query("SELECT COUNT(date) as data,date FROM entregas WHERE func_id = '$func_id' GROUP BY date");
while($row = mysql_fetch_assoc($result))
{
//That part I dont really know what to do
}}
Sorry for my english, I dont speak very well ):

You're looking for DAYOFWEEK
Example
SELECT DAYOFWEEK('2007-02-03');
Further info : DAYOFWEEK documentation

Related

Retrieving product count for each month in the current year laravel

I'm trying to count the number of orders for each month of the current year as follows
//month arrays to loop through
$month = ['1','2','3','4','5','6', '7', '8', '9', '10', '11','12'];
//current year
$year = Carbon::now()->year;
//variable to store each order coubnt as array.
$new_orders_count = [];
//Looping through the month array to get count for each month in the provided year
foreach ($month as $key => $value) {
$new_orders_count[] = Order::whereYear('updated_at', $year)
->whereMonth('updated_at',$value)
->where(['orders.status_id'=>11])
->orWhere(['orders.status_id'=>14])
->orWhere(['orders.status_id'=>4])->count();
}
This gives me the following result
Note that this is returning 48 even where it should return zero or a different value from 48, for example, months 6 through to 12 have no data thus I expect the query to return zero but it is not. Why is this and how can I achieve what I need? I'm using laravel's default timestamp format for the created_at and updated_at fields
//current year
$year = Carbon::now()->year;
//variable to store each order count as array.
$new_orders_count = [];
//Looping through the month array to get count for each month in the provided year
for($i = 1; $i <= 12; $i++){
$new_orders_count[] = Order::whereYear('updated_at', $year)
->whereMonth('updated_at', $i)
->where(function ($query) {
$query->whereIn('orders.status_id', [11, 14, 4]);
})->count();
}
Try like this way. change your query
Order::whereYear('updated_at', $year)
->whereMonth('updated_at', $value)
->where(function ($query) {
$query->whereIn('orders.status_id', [11, 14, 4]);
})->count();
may this help ...

Filter Data based on priority in LINQ

The fields in my Rate Table are Route, VehicleMasterId, VehicleType, Material, Client, UnitRate etc.
The priority order on which I have to fetch a single row is : VehicleNo > Route > Client > VehicleType, Material
Suppose I have 2 rows with same data except 1 has Client and Vehicle Type and the other one has VehicleNo.Then based on my priority, I should pick the rate of the row with VehicleNo.
To excute this In linq I have first picked all the rows with matching data. Here is my code.
public RateMasterDataModel GetRateMasterforCn(Consignment cn){
// I will always pass all the above fields in cn
var rateMaster = (from rate in Context.RateMaster
where rate.FromDate <= cn.Cndate
&& rate.ToDate >= cn.Cndate
&& (rate.VehicleTypeId != null ? rate.VehicleTypeId == cn.VehicleTypeId : true)
&& (rate.VehicleMasterId != null ? rate.VehicleMasterId == cn.VehicleMasterId : true)
&& (rate.ClientId != null ? rate.ClientId == cn.ClientId : true)
&& (rate.RouteId != null ? rate.RouteId == cn.RouteId : true)
&& (rate.MaterialMasterId != null ? rate.MaterialMasterId == cn.MaterialMasterId : true)
select new RateMasterDataModel
{
RateMasterId = rate.RateMasterId,
FromDate = rate.FromDate,
ToDate = rate.ToDate,
ClientId = rate.ClientId ,
VehicleMasterId = rate.VehicleMasterId,
VehicleTypeId = rate.VehicleTypeId,
MaterialMasterId = rate.MaterialMasterId,
UnitRate = rate.UnitRate,
LoadTypeId = rate.LoadTypeId,
LoadingPointId = rate.RouteId,
CalculationMasterId = rate.CalculationMasterId
}).ToList();
}
Please suggest how to filter after this.
You can use below code to get records ordered by VehicleNo > Route
.OrderBy(v=>v.VehicleNo).ThenBy(r=>r.RouteId)
Add multiple .ThenBy() clause as per your column requirement for sorting the data.
You mean to say if the row which doesn't have the vehicalno. filld-up then the row having Route must be selected.is it correct?

Conditional statements in PIG

I have below input in a text file and need to generate output in another file based on the logic.
Here is my input file:
customerid|Dateofsubscription|Customercode|CustomerType|CustomerText
1001|2017-05-23|455|CODE|SPRINT56
1001|2017-05-23|455|DESC|Unlimited Plan
1001|2017-05-23|455|DATE|2017-05-05
1002|2017-05-24|455|CODE|SPRINT56
1002|2017-05-24|455|DESC|Unlimited Plan
1002|2017-05-24|455|DATE|2017-05-06
Logic:
If Customercode = 455
if( CustomerType = "CODE" )
Val= CustomerText
if( CustomerType = "DESC" )
Description = CustomerText
if( CustomerType = "DATE" )
Date = CustomerText
Output:
customerid|Val|Description|Date
1001|SPRINT56|Unlimited Plan|2017-05-05
1002|SPRINT56|Unlimited Plan|2017-05-06
Could you please help me with this.
rawData = LOAD data;
filteredData = FILTER rawData BY (Customercode == 455);
--Extract and set Val/Description/Date based on CustomerText and 'null' otherwise
ExtractedData = FOREACH filteredData GENERATE
customerId,
(CustomerType == "CODE" ? CustomerText : null) AS Val,
(CustomerType == "DESC" ? CustomerText : null) AS Description,
(CustomerType == "DATE" ? CustomerText : null) AS Date;
groupedData = GROUP ExtractedData BY customerId;
--While taking MAX, all 'nulls' will be ignored
finalData = FOREACH groupedData GENERATE
group as CustomerId,
MAX($1.Val) AS Val,
MAX($1.Description) AS Description,
MAX($1.Date) AS Date;
DUMP finalData;
I have specified the core logic. Loading, formatting and storage should be straight-forward.
Filter the input where customercode=455,generate the required 2 columns,then group by customerid and then use BagToString
.
B = FILTER A BY Customercode == 455;
C = FOREACH B GENERATE $0 as CustomerId,$4 as CustomerText;
D = GROUP C BY CustomerId;
E = FOREACH D GENERATE group AS CustomerId, BagToString(C.CustomerText, '|'); -- Note:This will generate 1001,SPRINT56|Unlimited Plan|2017-05-05 so,you will have to concat the first field with '|' and then concat the resulting field with the second field which is already delimited by '|'.
F = FOREACH E GENERATE CONCAT(CONCAT($0,'|'),$1);
DUMP F;

Linq union all equivalent of sql code

I have the following queries:
var majorClients = maj in dbContext.MajorClients
where (maj.startdate > startDate)
where (maj.status == "Active")
Select new Client{EntityPK = maj.mjPrimaryKey,Name = maj.name, Type = "Maj"};
var minorClients = min in dbContext.MinorClients
where (min.startdate > startDate)
where (min.status == "Active" || min.status== "Inactive")
Select new Client{EntityPK = min.mnPrimaryKey,Name = min.name, Type = "Min"};
There are clients that could appear in both major and minor tables. I would like to return a list of all occurrences of clients in both tables, however if there are matching clients by name, then I would only want to return the matching record from the majorClients table.
I have written a sql query to return the results:
SELECT mjPrimaryKey AS EntityPK,name,'Maj' AS TYPE
FROM majorClients
WHERE status = 'Active' AND startDate > #startDate
UNION ALL
SELECT mnPrimaryKey,name,'Min' FROM minorClients
WHERE status IN ('Active','Inactive') AND startDate > #startDate
WHERE name NOT IN (SELECT name FROM majorClients WHERE status = 'Active' AND startDate > #startDate)
How would I represent this query in linq?
Try this linq. To exclude duplicates from minorClients, I've used Contains method. To union all objects - Union method:
var majorClients = from maj in dbContext.MajorClients
where maj.startdate > startDate
&& maj.status == "Active"
select new Client
{
EntityPK = maj.mjPrimaryKey,
Name = maj.name,
Type = "Maj"
};
var minorClients = from min in dbContext.MinorClients
where min.startdate > startDate
&& min.status == "Active" || min.status== "Inactive"
&& !(from maj in dbContext.MajorClients
where maj.startdate > startDate
&& maj.status == "Active"
select maj.name).Contains(min.Name)
select new Client
{
EntityPK = min.mnPrimaryKey,
Name = min.name,
Type = "Min"
};
var allClients = majorClients.Union(minorClients);

Fetch the desired result from below given DB table structure of MySQL

below are the table structures according to which I have to develop the desired output(given at the end)
tbl_docatr
docatr_id doc_id docatrtype_id docatr_float docatr_int docatr_date docatr_varchar docatr_blob
1 12 1 NULL NULL NULL testing [BLOB - NULL]
2 12 2 NULL NULL NULL Tesitng [BLOB - NULL]
tbl_docatrtype
docatrtype_id docatrtypegroup_id docatrtypetype_id docatrtype_name
1 1 4 Name
2 1 4 Company Name
tbl_docatrtypetype
docatrtypetype_id docatrtypetype_name
1 Float
2 Int
3 Date
4 String line
Above are three tables from which I have to display the desired output as
Name : testing
Company Name : Tesitng
such that at first step I have doc_id then I get docatrtype_id and then docatrtypetype_id acording to these values i have to fetch the result. Also the query must see the doactrtypetype_id from table tbl_docatrtypetype and fetch the result from tbl_docatr from respective column docatr_float, docatr_int, docatr_date, docatr_varchar, docatr_blob
UPDATE
I Have created the below PHP functions for the queries please help me to get the easy one
function getDocumentDetail($doc_id){
$arr_document_detail = array();
$query = "SELECT * FROM tbl_doc WHERE doc_id = '".$doc_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0) {
while($row = $this->connect->getRowArr()){
$arr_document_detail = $row;
}
}
return $arr_document_detail;
}
//Getting Attribute Details
function getAttributeDetails($doc_id){
$arr_attrtype_id = array();
$query = "SELECT
docatrtype_id,
docatr_float,
docatr_int,
docatr_varchar,
docatr_date,
docatr_blob
FROM
tbl_docatr
WHERE
doc_id = '".$doc_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0){
$j = 0;
while($row1 = $this->connect->getRowArr()){
$arr_attrtype_id[$j] =$row1;
$j++;
}
}
return $arr_attrtype_id;
}
function getAttrTypetype($attrtype_id){
$arr_attrtypetype = array();
$query = "SELECT
docatrtype_name,
docatrtype_id,
docatrtypegroup_id,
docatrtypetype_id
FROM
tbl_docatrtype
WHERE
docatrtype_id = '".$attrtype_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0){
$i = 0;
while($row1 = $this->connect->getRowArr()){
$arr_attrtypetype[$i] =$row1;
$i++;
}
}
return $arr_attrtypetype;
}
function getAttrtypetypedetail($attrtypetype_id){
$arr_attrtypetype_detail = array();
$query = "SELECT
docatrtypetype_name,
docatrtypetype_id
FROM
tbl_docatrtypetype
WHERE
docatrtypetype_id = '".$attrtypetype_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0){
$i = 0;
while($row1 = $this->connect->getRowArr()){
$arr_attrtypetype_detail[$i] =$row1;
$i++;
}
}
return $arr_attrtypetype_detail;
}
UPDATE--2 as per #Danosaure
select concat(dat.docatrtype_name, ':',
case dat.docatrtypetype_id
when '1' then da.docatr_float
when '2' then da.docatr_int
when '3' then da.docatr_date
when '4' then da.docatr_varchar
when '5' then da.docatr_blob
end) as 'Value'
from tbl_docatr da
inner join tbl_docatrtype dat using (docatrtype_id)
inner join tbl_docatrtypetype datt using (docatrtypetype_id)
WHERE da.doc_id=33
ORDER BY da.docatr_id;
For the sake of "integrity", you should add a (5, 'Blob') row to tbl_docatrtypetype.
select dat.docatrtype_name,
case datt.docatrtypetype_name
when 'Float' then da.docatr_float
when 'Int' then da.docatr_int
when 'Date' then da.docatr_date
when 'String line' then da.docatr_varchar
else da.docatr_blob
end as 'Value'
from tbl_docatr da
inner join tbl_docatrtype dat using (docatrtype_id)
inner join tbl_docatrtypetype datt using (docatrtypetype_id)
WHERE da.doc_id=12
ORDER BY da.docatr_id;
EDIT: Added doc_id specific values per OP comment.