How to make table name dynamic Postgresql - sql

This is my query which join the result of query performed in postgresql from one database with another query from another database the thing is the table's name in the seconde database depend on the result of the query that target the first database. Here is the query:
select
gdr.id ,
attachment_id ,
state ,
gdr.user_id ,
gdr.document_id ,
internal_code,
ia."name" ,
gdd.id,tb2.col_3095
from
gediso_document_record as gdr
inner join ir_attachment ia on ia.id = gdr.attachment_id
inner join gediso_document_descriptor gdd on gdd.document_id = gdr.document_id
inner join (
select * from dblink('dbname=gediso_document','select id,record_id,col_3095 from doc_id_'||gdr.id)
AS tb2(id int,record_id int,col_3095 varchar)
)AS tb2 ON tb2.record_id = gdr.id
where
gdr.user_id =2031
limit 100
The problem resides in this line { select * from dblink('dbname=gediso_document','select id,record_id,col_3095 from doc_id_'||gdr.id) }
It won't allow me to use gdr.id
Can anyone help me please ? Thank you in advance.

Related

SQL Server Loop Over Records

I have a view vwDocumentLinks with data as shown below:
I have another table RiskTypes with data as below.
The link between the table & viewis : Idx25 = Risk Type and LinkDocNo = DocumentType. What I am trying to achieve is to get DocumentType in RiskTypes that's not in the view vwDocumentLinks foreach BaseValue and where Idx25 = RiskType. An example using a single BaseValue will be:
SELECT * FROM RiskTypeDocuments WHERE RiskType = 'BUSINESS LIMITED COMPANY' AND DocumentType NOT IN (SELECT LINKDOCNO FROM DBO.VWLINKS WHERE BaseValue = '00007573-1637-4B8E-9374-730AF58BCFB6')
I tried the below query and it's not working as expected. Any help will be greatly appreciated. I am a newbie in SQL
SELECT dbo.RiskTypeDocuments.DocumentType,
dbo.RiskTypeDocuments.RiskType,
dbo.vwLinks.BaseValue AS Document
FROM dbo.vwLinks LEFT OUTER JOIN
dbo.RiskTypeDocuments ON dbo.vwLinks.LinkDocNo =
dbo.RiskTypeDocuments.DocumentType AND dbo.vwLinks.Idx25 =
dbo.RiskTypeDocuments.RiskType
WHERE dbo.RiskTypeDocuments.DocumentType IS NOT NULL
ORDER BY Document
NB: I can't change the schema. I can only create views from the existing tables.
Sample Data from the two datasets: vwDocumentLinks & RiskTypeDocuments
SELECT a.DocumentType,
a.RiskType,
b.BaseValue AS Document
FROM dbo.RiskTypeDocuments as a
INNER JOIN (Select distinct Idx25, BaseValue from vwDocumentLinks) as b on b.Idx25 = a.RiskType
where a.DocumentType not in (Select LINKDOCNO from vwDocumentLinks as c where c.basevalue = b.BaseValue )
I think what you are looking for is NOT EXISTS. It takes a little to get your head around, but the idea is to have what is called a correlated subquery. The subquery is joined to the main query, hence the term correlated.
SELECT *
FROM RiskTypeDocuments
WHERE NOT EXISTS (
SELECT 1 FROM vwDocumentLinks
WHERE RiskTypeDocuments.RiskType = vwDocumentLinks.idx25
AND RiskTypeDocuments.DocumentType = vwDocumentLinks.LinkDocNo
)
If you want to retrieve the records which don't exist in the view then
Try like this
SELECT d.DocumentType,
d.RiskType,
v.BaseValue
FROM dbo.vwLinks AS v
OUTER JOIN dbo.RiskTypeDocuments d ON v.LinkDocNo = d.DocumentType AND v.vwLinks.Idx25 =d.RiskType
WHERE v.BaseValue IS NULL
ORDER BY DocumentType

query get records lesser than SQL

This query which get records of all clubs, i check record per records. The NULL columns doesn't play any role. Howerver i filled NULL's. This mean any NULL isn't existing.
This query get 202 recordcount using cfquery and on MSSQL 2014 get 204 records.
Could you please tell what could happen that cfquery can't get some records. The exact query work on MSSQL 2014 perfectly.
SELECT tblDistrict.IDDist,
tblClubs.IDDiv,
tblClubs.ClubArtStart,
tblClubs.IDClub,
tblClubs.ClubName,
tblDivisionen.DivBezeichnung,
tblDivisionen.Region,
tblClubs.OrgDatum,
tblClubs.ChartDatum,
tblClubs.ClubStatus,
tblClubs.ClubArt,
tblClubs.Clubort
FROM (tblDistrict
INNER JOIN tblDivisionen ON tblDistrict.IDDist = tblDivisionen.IDDist)
INNER JOIN tblClubs ON tblDivisionen.IDDiv = tblClubs.IDDiv
WHERE (((tblDistrict.IDDist)=1)) AND Clubstatus<>'E' AND Clubstatus<>'I'
I would start with some formatting and aliasing. Your query would look something like this. This would be a lot more maintainable.
SELECT d.IDDist
, c.IDDiv
, c.ClubArtStart
, c.IDClub
, c.ClubName
, div.DivBezeichnung
, div.Region
, c.OrgDatum
, c.ChartDatum
, c.ClubStatus
, c.ClubArt
, c.Clubort
FROM tblDistrict d
INNER JOIN tblDivisionen div ON d.IDDist = div.IDDist
INNER JOIN tblClubs c ON div.IDDiv = c.IDDiv
WHERE d.IDDist = 1
AND c.Clubstatus not in ('E', 'I')

Multiple Joins And Writing to Destination Table with BigQuery

I have the following query that works fine if I DON'T set a destination table.
SELECT soi.customer_id
, p.department
, p.category
, p.subcategory
, p.tier1
, p.tier2
, pc.bucket as categorization
, SUM(soi.price) as demand
, COUNT(1) as cnt
FROM store.sales_item soi
INNER JOIN datamart.product p ON (soi.product_id = p.product_id)
INNER JOIN daily_customer_fact.dcf_product_categorization pc
ON (p.department = pc.department
AND p.category = pc.category
AND p.subcategory = pc.subcategory
AND p.tier1 = pc.tier1
AND p.tier2 = pc.tier2)
WHERE DATE(soi.created_timestamp) < current_date()
GROUP EACH BY 1,2,3,4,5,6,7 LIMIT 10
However, if I set a destination table, it fails with
Error: Ambiguous field name 'app_version' in JOIN. Please use the table qualifier before field name.
That column exists on the store.sales_item table, but I'm not selecting nor joining to that column.
I've seen this error message before, and it points to the following:
Your query job when specifying a destination table is setting flattenResults to false.
Both of the store.sales_item and datamart.product tables contain a field named "app_version".
If so, I recommend looking at this answer:
https://stackoverflow.com/a/28996481/4001094
As well as this issue report: https://code.google.com/p/google-bigquery/issues/detail?id=459
In your case, you should be able to make your query succeed by doing something like the following, using suggestion #3 from the answer linked above. I'm unable to test it as I don't have access to your source tables, but it should be close to working with flattenResults set to false.
SELECT soi_and_p.customer_id
, soi_and_p.department
, soi_and_p.category
, soi_and_p.subcategory
, soi_and_p.tier1
, soi_and_p.tier2
, pc.bucket as categorization
, SUM(soi_and_p.price) as demand
, COUNT(1) as cnt
FROM
(SELECT soi.customer_id AS customer_id
, p.department AS department
, p.subcategory AS subcategory
, p.tier1 AS tier1
, p.tier2 AS tier2
, soi.price AS price
, soi.created_timestamp AS created_timestamp
FROM store.sales_item soi
INNER JOIN datamart.product p ON (soi.product_id = p.product_id)
) as soi_and_p
INNER JOIN daily_customer_fact.dcf_product_categorization pc
ON (soi_and_p.department = pc.department
AND soi_and_p.category = pc.category
AND soi_and_p.subcategory = pc.subcategory
AND soi_and_p.tier1 = pc.tier1
AND soi_and_p.tier2 = pc.tier2)
WHERE DATE(soi_and_p.created_timestamp) < current_date()
GROUP EACH BY 1,2,3,4,5,6,7 LIMIT 10

Doctrine, How can I do a select * (all) statememt?

I'm trying to mimic this sql query:
$sql = "SELECT *, log.id as logid, date_format(shipdate,'%m/%d/%Y') as shipdate
FROM log LEFT JOIN sub ON sub.id = sub_id
LEFT JOIN main ON id = main_id WHERE
shipdate >= '$datestart' AND shipdate <= '$dateend' ";
When I put SELECT * in the createQuery function of Doctrine, an error says it doesn't recognize that statement so I tried to grab all the entities by selecting individual ones:
$query = $this->getEntityManager()
->createQuery('
SELECT
m.dano, m.partno, m.batchno,
s.rackno, s.heatcode, s.diecode,
l.shipdate, l.qtyshipped, l.blno, l.id as logid
FROM
Bundle:Sub s
JOIN
s.main m
JOIN
s.log l
WHERE
l.shipdate >= :fromdate and l.shipdate <= :todate
')->setParameter('fromdate', $fromdate)
->setParameter('todate', $todate);
However when I do it this way, it doesn't return all the data that the original queries does. It skips some rows. Is there another way to be selecting all the entity?
You can mimic the following SQL using DQL. I believe that's the best way to do rather than using create query. Select all in DQL is 'select(alias)'. See my
SELECT *, log.id as logid, date_format(shipdate,'%m/%d/%Y') as shipdate
FROM log LEFT JOIN sub ON sub.id = sub_id
LEFT JOIN main ON id = main_id WHERE
shipdate >= '$datestart' AND shipdate <= '$dateend'
DQL
$dql = $qb2->select('m.dano, m.partno, m.batchno,
s.rackno, s.heatcode, s.diecode,
l.shipdate, l.qtyshipped, l.blno, l.id')
->from('YourBundle:Log','l')
->leftJoin('l.sub', 's', Expr\Join::ON, 's.id = l.sub_id')
->leftJoin('l.main', 'm', Expr\Join::ON, 'm.id = l.main_id')
->where('l.shipdate >= :shipdateStart')
->setParameter('shipdateStart', $datestart)
->where('l.shipdate <= :shipdateEnd')
->setParameter('shipdateEnd', $dateend)
By the way your selecting table and joining tables are slightly different in the given sql example compared to your query in create query function. I mimiced what's in your raw SQL which is listed above. Hope this helps you to understand converting SQL in to DQL.
Regards,

sql server update from select

Following the answer from this post, I have something like this:
update MyTable
set column1 = otherTable.SomeColumn,
column2 = otherTable.SomeOtherColumn
from MyTable
inner join
(select *some complex query here*) as otherTable
on MyTable.key_field = otherTable.key_field;
However, I keep getting this error:
The column prefix 'otherTable' does
not match with a table name or alias
name used in the query.
I'm not sure what's wrong. Can't I do such an update from a select query like this?
Any help would be greatly appreciated.
(I'm using *blush* sql server 2000.)
EDIT:
here's the actual query
update pdx_projects set pr_rpc_slr_amount_year_to_date = summary.SumSLR, pr_rpc_hours_year_to_date = summary.SumHours
from pdx_projects pr join (
select pr.pr_pk pr_pk, sum(tc.stc_slr_amount) SumSLR, sum(tc.stc_worked_hours) SumHours from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sl.sol_fk = sp.sol_pk
join pdx_projects pr on pr_pk = sl.pr_fk
where tc.stc_time_card_year = year(getdate())
group by pr_pk
) as summary
on pr.pr_pk = summary.pr_pk
and the actual error message is
Server: Msg 107, Level 16, State 2,
Line 1 The column prefix 'summary'
does not match with a table name or
alias name used in the query.
I submit to you this altered query:
update x
set x.pr_rpc_slr_amount_year_to_date = summary.sumSLR,
x.pr_rpc_hours_year_to_date = summary.sumHours
from pdx_projects x
join (
select pr.pr_pk as pr_pk,
sum(tc.stc_slr_amount) as SumSLR,
sum(tc.stc_worked_hours) as SumHours
from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sp.sol_pk = sl.sol_fk
join pdx_projects pr on sl.pr_fk = pr.pr_pk
where tc.stc_time_card_year = year(getdate())
group by pr.pr_pk
) as summary
on x.pr_pk = summary.pr_pk
Notably different here: I don't re-use the alias pr inside and outside of the complex query. I re-ordered the joins the way I like them (previously referenced table first,) and explicitly notated pr_pk in 2 places. I also changed the update syntax to use update <alias>.
Maybe not the answer you're looking for, but instead of generating hugely complex queries, I usually default to inserting the some complex query here into a table variable. Then you can do a simple update to MyTable with a join to the table variable. It may not be quite as efficient, but its much easier to maintain.
I couldn't replicate your error using SQL 2008 in 80 compatibility level. While this option doesn't guarantee that I'll get the same results as you, nothing appears to be out of place.
create table pdx_projects
(
pr_rpc_slr_amount_year_to_date varchar(max)
, pr_rpc_hours_year_to_date varchar(max)
, pr_pk varchar(max)
)
create table pdx_time_and_cost_from_rpc
(
stc_slr_amount decimal
, stc_worked_hours decimal
, stc_rpc_project_id varchar(max)
, stc_time_card_year varchar(max)
)
create table pdx_rpc_projects
(
sol_rpc_number varchar(max)
, sol_pk varchar(max)
)
create table pdx_rpc_links
(
sol_fk varchar(max)
, pr_fk varchar(max)
)
update pdx_projects
set
pr_rpc_slr_amount_year_to_date = summary.SumSLR
, pr_rpc_hours_year_to_date = summary.SumHours
from
pdx_projects pr
join (
select pr.pr_pk pr_pk
, sum(tc.stc_slr_amount) SumSLR
, sum(tc.stc_worked_hours) SumHours
from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sl.sol_fk = sp.sol_pk
join pdx_projects pr on pr_pk = sl.pr_fk
where tc.stc_time_card_year = year(getdate())
group by pr_pk
) as summary
on pr.pr_pk = summary.pr_pk