How to find the specific record using sub query in SQL - sql-server

I have a table in my Database in which Electronics part number information is saved. Against each part number, a Datasheet is attached with the Pdf file name and with its Publication date in next column.
There are some parts where pdf with different publication date is attached and I want to find out the Latest publication date pdf file.
Below is the code that I applied:
(
select v_prt_nbr_spr, max(s_gph_co_date), s_gph_file_name
from export1
where v_prt_nbr_spr = '747845-4'
group by v_prt_nbr_spr, s_gph_file_name
)
But I am getting multiple Pdf file name instead of the latest date as I am using group by clause..
Output:
v_prt_nbr_spr s_gph_co_date s_gph_file_name
747845-4 01-07-2001 TYELD00008.pdf
747845-4 14-03-2011 TYELS72963.pdf
747845-4 04-03-2016 TYEL-S-A0001601863.pdf
I want only TYEL-S-A0001601863.pdf name to show as it is the latest date pdf file.

You can try this:
select top 1
v_prt_nbr_spr, s_gph_co_date, s_gph_file_name
from export1
where v_prt_nbr_spr = '747845-4'
order by s_gph_co_date desc

Related

Oracle APEX - Download selected files as zip - IR/IG checkbox selection

I referred to this link create a download zip button to download files in zip format in Oracle apex latest version 22.2. It is working fine without any issues but only concern is; it downloads all the files in one zip file. Whereas my requirement is to include a checkbox on a report (either IG or IR) and to download selected files in one zip file.
Below is the table I am referring to. Its from Oracle apex sample files upload and download.
select
ID,
ROW_VERSION_NUMBER,
PROJECT_ID,
FILENAME,
FILE_MIMETYPE,
FILE_CHARSET,
FILE_BLOB,
FILE_COMMENTS,
TAGS,
CREATED,
CREATED_BY,
UPDATED,
UPDATED_BY
from EBA_DEMO_FILES
I tried searching over the internet and found few links pointing to APEX_ZIP, PL/SQL compress blob etc. But could not see any demo or working model similar to the link I provided above.
If anybody has working demo or blog,I request to share it. Many thanks.
Update: As suggested by Koen Lostrie, I am updating Page process code below:
DECLARE
l_id_arr apex_t_varchar2;
l_selected_id_arr apex_t_varchar2;
var_zip blob;
BEGIN
-- push all id values to an array
FOR i IN 1..APEX_APPLICATION.G_F03.COUNT LOOP
apex_string.push(l_id_arr,APEX_APPLICATION.G_F03(i));
FOR j IN 1 .. APEX_APPLICATION.G_F01.COUNT LOOP
IF APEX_APPLICATION.G_F01(j) = APEX_APPLICATION.G_F03(i) THEN
-- push all selected emp_id values to a 2nd array
apex_string.push(l_selected_id_arr,APEX_APPLICATION.G_F03(i));
END IF;
END LOOP;
END LOOP;
-- Create/clear the ZIP collection
APEX_COLLECTION.CREATE_OR_TRUNCATE_COLLECTION(
p_collection_name => 'ZIP');
-- Loop through all the files in the database
begin
for var_file in (select fi.filename, fi.file_blob, pr.project
from eba_demo_files fi
inner join eba_demo_file_projects pr on fi.project_id = pr.id
where fi.id in (SELECT column_value FROM table(apex_string.split(apex_string.join(l_selected_id_arr,':'),':'))))
loop
-- Add each file to the var_zip file
APEX_ZIP.ADD_FILE (
p_zipped_blob => var_zip,
p_file_name => var_file.project || '/' || var_file.filename,
p_content => var_file.file_blob );
end loop;
exception when no_data_found then
-- If there are no files in the database, handle error
raise_application_error(-20001, 'No Files found!');
end;
-- Finish creating the zip file (var_zip)
APEX_ZIP.FINISH(
p_zipped_blob => var_zip);
-- Add var_zip to the blob column of the ZIP collection
APEX_COLLECTION.ADD_MEMBER(
p_collection_name => 'ZIP',
p_blob001 => var_zip);
END;
Once page process is done, follow step 3 and 4 from the link provided in OP.
Below is the updated query:
select
ID,
ROW_VERSION_NUMBER,
PROJECT_ID,
FILENAME,
FILE_MIMETYPE,
FILE_CHARSET,
FILE_BLOB,
FILE_COMMENTS,
TAGS,
CREATED,
CREATED_BY,
UPDATED,
UPDATED_BY,
APEX_ITEM.CHECKBOX(1,ID) checkbox,
APEX_ITEM.TEXT(2,FILENAME) some_text,
APEX_ITEM.HIDDEN(3,ID) hidden_empno
from EBA_DEMO_FILES
Big Thanks to Koen Lostrie.
All credits goes to Koen Lostrie.
Thanks,
Richa
This is just an answer to the last comment - the base question was answered in the comments. The question in the comment is "how do I include APEX_ITEM.HIDDEN columns in my report without hiding the columns".
When the columns are hidden in the report, they're not rendered in the DOM, so the values do not exist when the form is posted. That is the reason you're getting the error.
However, take a step back and check what APEX_ITEM.HIDDEN generates. Add a column of type APEX_ITEM.HIDDEN to the report and inspect the column in the browser tools. It generates an input element of type "hidden", so the value is not shown in the report. So to include the column in your report but not make it visible on the screen, just concatenate it to an existing other column:
In your case, with the select from the question that would be:
select
APEX_ITEM.HIDDEN(3,ID) || APEX_ITEM.HIDDEN(2,FILENAME) || ID,
ROW_VERSION_NUMBER,
PROJECT_ID,
FILENAME,
FILE_MIMETYPE,
FILE_CHARSET,
FILE_BLOB,
FILE_COMMENTS,
TAGS,
CREATED,
CREATED_BY,
UPDATED,
UPDATED_BY,
APEX_ITEM.CHECKBOX(1,ID) checkbox
from EBA_DEMO_FILES
Note that filename can also be in a hidden element.

How to generate an excel file (.xlsx) from SQL Server

I have this query:
WITH InfoNeg AS
(
SELECT DISTINCT
n.idcliente,
CASE
WHEN DATEDIFF(MONTH, MAX(n.fechanegociacion), GETDATE()) <= 2
THEN 'Negociado 6 meses'
ELSE NULL
END AS TipoNeg
FROM
SAB2NewExports.dbo.negociaciones AS n
WHERE
Aprobacion = 'Si'
AND cerrado = 'Si'
GROUP BY
n.idcliente
), Multi AS
(
SELECT DISTINCT
idcliente, COUNT(distinct idportafolio) AS NumPorts
FROM
orangerefi.wfm.wf_master_HIST
WHERE
YEAR(Fecha_BKP) = 2021
AND MONTH(Fecha_BKP) = 08
GROUP BY
idcliente
)
SELECT DISTINCT
m.IdCliente, c.Nombre1
FROM
orangerefi.wfm.wf_master_HIST as m
LEFT JOIN
InfoNeg ON m.idcliente = InfoNeg.idcliente
LEFT JOIN
Multi ON m.IdCliente = Multi.idcliente
LEFT JOIN
SAB2NewExports.dbo.Clientes AS c ON m.IdCliente = c.IdCliente
WHERE
CanalTrabajo = 'Callcenter - Outbound' -- Cambiar aca
AND YEAR (Fecha_BKP) = 2021
AND MONTH(Fecha_BKP) = 08
AND GrupoTrabajo IN ('Alto') -- Cambiar aca
AND Bucket IN (1, 2) -- Cambiar aca
AND Multi.NumPorts > 1
AND Infoneg.TipoNeg IS NULL
When I run it, I get 30 thousand rows and the columns that I get when performing the query are: ClientID, name. I would like it to be saved in an Excel file when I run it, I don't know if it's possible.
Another question, is it possible to create a variable that stores text?
I used CONCAT(), but the text being so long is a bit cumbersome, I don't know if there is any alternative.
If you can help me, I appreciate it.
To declare a variable
DECLARE #string VARCHAR(MAX)
SET #string = concat()
then insert whatever you are concatenating
Here is an answer given by carusyte
Export SQL query data to Excel
I don't know if this is what you're looking for, but you can export the results to Excel like this:
In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV.
You might give this a shot too:
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
Lastly, you can look into using SSIS (replaced DTS) for data exports. Here is a link to a tutorial:
http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm
== Update #1 ==
To save the result as CSV file with column headers, one can follow the steps shown below:
Go to Tools->Options
Query Results->SQL Server->Results to Grid
Check “Include column headers when copying or saving results”
Click OK.
Note that the new settings won’t affect any existing Query tabs — you’ll need to open new ones and/or restart SSMS.

Need to select bucket name while reading from s3 stage

I am reading from S3 folder in snowflake via stage.
The bucket in s3 have multiple folder (or object if we want to call it).
The folder is on date basis in the bucket
date=2020-06-01
date=2020-06-02
date=2020-06-03
date=2020-06-04
date=2020-06-05
I am using the below query to read all the folder at once. which is just working fine.
select raw.$1:name name,
raw.$1:id ID
from
#My_Bucket/student_date/
(FILE_FORMAT => PARQUET,
PATTERN =>'.*date=.*\gz.parquet') raw
;
Now i want to select the folder name as well in my query, Is there a way to do it.
like the output to contain
name | id | date..
pleas suggest
Snowflake has a built-in metadata field that provides the full filename, including the path. You should be able to run the following query:
select raw.$1:name name,
raw.$1:id ID,
METADATA$FILENAME
from
#My_Bucket/student_date/
(FILE_FORMAT => PARQUET,
PATTERN =>'.*date=.*\gz.parquet') raw
;
I know you are after the date portion only, but once you have the filename, you can use the SPLIT_PART function to get the date part from the filename. e.g.
SPLIT_PART(METADATA$FILENAME, '/', 4)
Hope this helps.

select geometry from geopackage in dbbrowser for sqlite

I'm using dbmanager for sqlite with spatialite module loaded and I'm trying to read a geopackage I exported before from qgis 3.12.
I perform this both selections bellow and get the 'geometry' with hex function, and them as supposed WKT text (I'm not sure) but when I export it as csv to read in qgis again, it didn't work. I read some examples from sqlite docs to select it as AsText or AsBinary or other readable type in qgis, but it only return empty field.
Functions here: http://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html#p16gpkg
First case:
SELECT cd_geocodi, nm_bairro, renmeddom, SRID(geom), hex(geom) from
setorcengeom_rj20171016 where renmeddom > 5000 group by cd_geocodi
order by nm_bairro DESC limit 10;
Second case:
SELECT cd_geocodi, nm_bairro, renmeddom, SRID(geom) as epsg,
AsText(CastAutomagic(geom)) AS geometry from setorcengeom_rj20171016
where renmeddom > 5000 group by cd_geocodi order by nm_bairro DESC
limit 30;
I believe I got the answer! I sucefully export it as CSV and load it in QGIS with no problems.
> SELECT cd_geocodi, nm_bairro, renmeddom, SRID(geom) as epsg,
> AsWKT(CastAutomagic(geom)) AS geometry from setorcengeom_rj20171016
> group by cd_geocodi order by nm_bairro DESC

How can i use a sharepoint list as a view in SQLServer

I have a sharepoint site and i create a list on it. I want to join this list with a SQLServer table. I have access to Sharepoint DB in SQLServer and i maked a new table in this DB. My problem is that i can not find my list in Sharepoint DB to join with this new table.
How can i do this.
You should not access the SharePoint DB even if only for reading. But if you want to do this, there is no documentation on that (no db model). There are some posts about this on the web like Where does SharePoint store list items or HOW TO PULL SHAREPOINT LIST DATA FROM SQL SERVER.
SELECT
ud.tp_ID
, ud.tp_ListId
, ud.tp_Author
, ud.nvarchar1
, ud.nvarchar2
, ud.nvarchar3
, ud.nvarchar4
, ud.nvarchar5
, ud.nvarchar6
, ud.nvarchar7
, ud.nvarchar8
, ud.nvarchar9
, ud.nvarchar10
, ud.nvarchar11
, ud.nvarchar12
, ud.*
FROM dbo.AllLists l
INNER JOIN dbo.AllUserData ud ON l.tp_ID = ud.tp_ListId
WHERE (ud.tp_ListId = ‘{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}’)
In SP2013 the DB model has changed and the data of the lists is now stored as XML in the AllUserData table in the column tp_ColumnSet.
I finally solve my problem and share it to help you. There is a DB in sql server with name WSS_Content that you can find the dbo.AllUserData table. List data in SharePoint, saved in this table:
If you select data from this table, you can see a column with the name: [tp_ColumnSet] that has data.
You must find out which column has your data and finally create a view by this column's name like this:
SELECT ntext2 AS Url, nvarchar1 AS Title, nvarchar5 AS FileName
FROM dbo.AllUserData

Resources