Postgres how to find numeric element in json array (revision) - arrays

table name: muscle_groups
fields: id, name, segment_ids
data:
{"f": [], "m": [31, 32, 33, 34, 35, 36, 38, 39]}
tried many variations like:
select id, name, segment_ids->>"m"
where 5 = any(json_array_element(segment_ids->>"m")

You are looking for the contains operator #>
select *
from muscle_groups
where segment_ids #> '{"m": [5]}'

Related

struct unpack error when converting datetime(2) datatype in SQL Server to string

def datetime_as_string(raw_bytes):
#
tup = struct.unpack('8h', raw_bytes)
print(tup)
return datetime.datetime(tup[0], tup[1], tup[2], tup[3], tup[4], tup[5], 0).strftime('%Y-%m-%d %H:%M:%S.%f')
I am writing this function to unpack datetime.datetime(2022, 11, 18, 13, 42, 31, 316666) with data type datetime2(7) in SQL Server to convert it to a string but I am unable to do this as it unpacks to (2022, 11, 18, 13, 42, 31, -3252, 4831) whereas I was expecting it to unpack it to (2022, 11, 18, 13, 42, 31, 316666).
I am unable to figure out how to if condition to check between datetime2(7) and datetime. When I don't use the output converter in pyodbc the query returned is like this
('103345', datetime.datetime(2022, 6, 9, 13, 51, 42, 856667), datetime.datetime(2022, 6, 9, 13, 51, 42, 856667), '2022-06-09', 'ENTRY', 'ENTRY')
and I want it to be something like this
('103345', '2022-06-09 13:51:42.856667', '2022-06-09 13:51:42.856667', '2022-06-09', 'ENTRY', 'ENTRY')
Kindly help me figure where I might be doing wrong.
The other part of my script which is working correctly and converting date datatype to string when I comment the above function.
def convert_date_to_string(raw_bytes):
tup = struct.unpack('3h', raw_bytes)
# print(tup)
return datetime.date(tup[0], tup[1], tup[2]).strftime('%Y-%m-%d')
# check if the connection is successful
def test_query():
try:
conn = po.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
# add converter for datetime and date
conn.add_output_converter(po.SQL_TYPE_TIMESTAMP, datetime_as_string)
conn.add_output_converter(po.SQL_TYPE_DATE, convert_date_to_string)
print("Connection Successful")
except Exception as e:
print("Connection Failed")
print(e)
Tldr; I am trying to get output of sql query in pyodc as string rather than datetime.datetime() object for which I wrote a output converter function and I get this error
struct unpack error 8 bytes buffer required
or
unpacking incorrectly

CakePHP: How to Code in Cakephp 4 with Multiple LEFT JOINS Where One LEFT JOIN Is Not Associated to the Main Table

OBJECTIVE:
DISPLAY A LIST OF:
MEMBER ID/ MEMBER NAME/ DATE VISITED/ MEMBER'S GRADE
This is the SQL statement I want to code in CakePHP 4:
SELECT visits.member_id, members.mbr_name, visits.created, batches.grade_id
FROM visits
LEFT JOIN members ON members.mbrid = visits.member_id
LEFT JOIN batches ON batches.member_id = members.mbrid
WHERE batches.batch = '2020' AND (batches.sub_batch = '0' OR batches.sub_batch = '1')
ORDER BY visits.created DESC
As you can see, the second LEFT JOIN clause is only related to members, instead of the main table visits.
This is the way I code it in CakePHP 4:
$this->Visits->find()
->contain('Members.Batches', function (Query $q) {
return $q
->select('member_id', 'batch', 'sub_batch', 'grade_id')
->where(['Batches.batch' => '2020', 'Batches.sub_batch' => '0']);
})
->contain('Members')
->order(['Visits.created' => 'DESC'])
);
In the Debug mode, I can see two(2) SQL generated. Not what I expected:
SELECT
Visits.id AS Visits__id,
Visits.member_id AS Visits__member_id,
Visits.vst_datetime AS Visits__vst_datetime,
Visits.location_id AS Visits__location_id,
Visits.created AS Visits__created,
Visits.modified AS Visits__modified,
Members.id AS Members__id,
Members.mbrid AS Members__mbrid,
Members.mbr_name AS Members__mbr_name,
Members.mbr_type AS Members__mbr_type,
Members.created AS Members__created,
Members.modified AS Members__modified
FROM
visits Visits
LEFT JOIN members Members ON Members.mbrid = (Visits.member_id)
ORDER BY
Visits.created DESC
LIMIT
20 OFFSET 0
SELECT
Batches.member_id AS Batches__member_id
FROM
batches Batches
WHERE
(
Batches.member_id in (
187, 1471, 1470, 1463, 250, 350, 1000,
501, 300, 255, 254, 253, 3, 303, 215,
305, 202, 201
)
AND Batches.batch = '2020'
AND Batches.sub_batch = '0'
)
Here's the code that gives me the sql that I need:
$visits = $this->Paginator->paginate($this->Visits->find()
->select(['Members.mbrid', 'Members.mbr_name', 'Visits.created', 'Batches.grade_id'])
->leftJoinWith('Members')
->leftJoinWith('Members.Batches')
->where(['Batches.batch' => '2020', 'Batches.sub_batch' => '0'])
->order(['Visits.created' => 'DESC'])
);
As suggested by #ndm by using leftJoinWith.

Mongodb Aggregate lookup all products from one specific client

I have a Database from a .data and these collections: clientes, mercancias and vagones. I want to find all the data of mercancias from the same client. So in this case, "Electronica Chispas" has 2 "mercancia" entities in the database:
[{"cliente": {"nombre": "Cafes el amanencer"},
"mercancia": {"envio": "Normal", "tipo": "Gaseoso", "fecha": "24/12/2003", "peso": 21, "volumen": 43, "origen": "Cadiz", "destino": "Castellon"},
"vagon": {"id": 1330, "volumen": 202, "peso": 433 }},{"cliente": {"nombre": "Electronica Chispas"}, "mercancia": {"envio": "Normal", "tipo": "Liquido", "fecha": "08/02/2005", "peso": 17, "volumen": 24, "origen": "San Sebastian", "destino": "Orense"}, "vagon": {"id": 1290, "volumen": 111, "peso": 464 }},{"cliente": {"nombre": "Electronica Chispas"}, "mercancia": {"envio": "Urgente intradia", "tipo": "Contaminante", "fecha": "15/09/2002", "peso": 11, "volumen": 83, "origen": "Valladolid", "destino": "Ciudad Real"}, "vagon": {"id": 1315, "volumen": 115, "peso": 481 }}]
I am trying this query:
db.mercancias.aggregate([{$lookup:{'from': 'clientes', 'localField':'destino', 'foreignField': 'nombre', 'as': 'clientes'}}])
But it is not working how I want to. Of course, I am missing to write the "Electronica Chispas" name somewhere in that query, but I am not sure where to write it.
In MongoDB, having duplicate data is not important nor an issue!
Making how to join was impossible. I decided to add in mercancias an id of vagonand nombreof clientes, so the relation could be named. That way, there was no need to do LookUpin mongo, and a "simple" aggregate query could be done!

create a i*j struct array in matlab

After searching on the internet, I know how to create a 1*j struct array. For example,
>> patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
>>
>> patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
My question is: how to create a j*1 struct array? Thanks so much for your time and attention.
There are two solutions:
You transpose your structure array afterwards:
patient = patient';
You index your structure array with two integers (first=row, second=column):
patient(j,1).name = 'John Doe';
Best,

PostgreSQL update one of jsonb array by the condtion child's key

In PostgreSQL, my column type is json , the data is json array like:
[{"attsId": "42a2ce04-52ab-4a3c-8dfb-98c3d14b307d", "planId": 46, "filePath": "fileOperate\\upload", "cfileName": "潜在客户名单 (1).xls", "ufileName": "42a2ce04-52ab-4a3c-8dfb-98c3d14b307d.xls"}, {"attsId": "1adb2f13-00b0-4780-ae76-7a068dc3289c", "planId": 46, "filePath": "fileOperate\\upload", "cfileName": "潜在客户名单.xls", "ufileName": "1adb2f13-00b0-4780-ae76-7a068dc3289c.xls"}, {"attsid": "452f6c62-28df-47c7-8c30-038339f7b223", "planid": 48.0, "filepath": "fileoperate\\upload", "cfilename": "技术市场印花税.xls", "ufilename": "452f6c62-28df-47c7-8c30-038339f7b223.xls"}]
I want update one of the array data by element key like:
UPDATE plan_base
set atts->.. = {"planId":47,"name":"qm"}
where atts->"planId"= 46 and id=2;
and someone has beterr way to do it

Resources