Using crosstab and adding new value to a column in postgresql - postgresql

I have a function (sae_rel_data())that returns a result like the one showing in the picture. I am trying to return the result as table event_crf_id, description, value, CBID instead. So I would have to identify the CBID value and assign that value to all other rows that has the same evet_crf_id in another column named CBID.
For example CBID= 60051 has event_crf_id=444
event_crf_id; description; value; CBID
444; "CBID"; "60051"; "60051"
444; "Month"; "09"; "60051"
444; "Day"; "27"; "60051"
444; "Year"; "2016"; "60051"
...
How can it be done? I am using postgresql

I was able to get the result I wanted by using breaking down my code and saving portions of it into a function and then applying inner join
SELECT cbid, description, value FROM (
SELECT test.event_crf_id, description, test.value, id_table.cbi FROM sae_rel_data() test
INNER JOIN (SELECT event_crf_id, value as cbid FROM sae_rel_data() where description='CBID') id_table
ON id_table.event_crf_id=test.event_crf_id )relevant

Related

more than one row returned by a subquery used as an expression problem

I am trying to update a column in one database with a query:
Here the query
and this is the output i think it is impossible to asign a query to a field but what is the solution for that plz.
enter image description here
= can be used when we are pretty sure that the subquery returns only 1 value.
When we are not sure whether subquery returns more than 1 value, we will have to use IN to accommodate all values or simply use TOP 1 to limit the equality matching to one value:
UPDATE mascir_fiche SET partner = (SELECT TOP 1 id FROM hr_employee WHERE parent_id IN (SELECT id FROM hr_employee));
With Limit:
UPDATE mascir_fiche SET artner = (SELECT id FROM hr_employee WHERE parent_id IN (SELECT id FROM hr_employee) limit 1);

Single Value Expression in When Then Aggregate Function TSQL

I am trying to map a certain value of a column based on its count on another table. If the count of [Location] i.e a column of IMPORT.DATA_SCRAP table in each row. For now for location static value i.e Utah and Kathmandu is supplied for test purpose only is equal to 1, then only i need to get the result in the select statement i.e only single value expression must be returned but here n rows of table with value is returned.
For. eg. In the below query,total rows of IMPORT.DATA_SCRAP gets returned, i only need the single first row value in my case.
I came to know whether cursor or CTE will acheive my result but i am unable to figure it out.
Here,
select
case
when
((SELECT COUNT(stateName) FROM Location.tblState where stateName = 'Utah')=1)
then (select stateName, CountryName from Location.tblState where stateName= 'Utah')
end as nameof
from IMPORT.DATA_SCRAP
The relation between country, state, city is as below:
select
case
when
((SELECT COUNT(cityName) FROM Location.tblCity where cityName = 'Kathmandu')=1)
then (select ct.countryName from Location.tblCity c
inner join Location.tblState s
on c.stateID = s.StateID
inner join Location.tblCountry ct
on ct.countryId = s.CountryId
where c.cityName = 'Kathmandu'
)
end as nameof
from IMPORT.DATA_SCRAP
How can i return only a single value expresion despite of multiple nmax rows of IMPORT.DATA_SCRAP row in the result.
If i comment out the -- from IMPORT.DATA_SCRAP in the above query i would get the desired single result expression in my case, but unable how can i acheive it in other ways or suggest me the appropriate way to do these types of situation.

Custom column from Joined table unknown

I created a resourcemodel for my Grid table that contains a custom query that joins 2 table. The sales_order and the sales_payment_transaction are joined to display all records that has a payment. Below is my query
protected function _initSelect()
{
parent::_initSelect();
$this->getSelect()
->joinLeft(
['spt' => $this->getTable('sales_payment_transaction')],
'main_table.entity_id = spt.order_id',
['spt.created_at as date_paid']
)
->where('main_table.status in ("complete", "processing")')
->order('main_table.entity_id DESC');
$this->addFilterToMap('created_at', 'main_table.created_at');
return $this;
}
As you can see in my custom column I added a new column which is the spt.created_at with a name of date_paid this new column is use for date filtering. So whenever I filter the order by date is uses the date_paid as a parameter. Now when viewing the logs I get this error
SELECT COUNT(*) FROM `sales_order` AS `main_table`
LEFT JOIN `sales_payment_transaction` AS `spt`
ON main_table.entity_id = spt.order_id
WHERE (main_table.status in (\"complete\", \"processing\"))
AND (`date_paid` >= '2021-01-03 00:00:00')
AND (`date_paid` <= '2021-10-03 22:59:59')
/// Column not found: 1054 Unknown column 'date_paid' in 'where clause'
it seems that it can't recognize the new column. May I know how to properly construct this query?
It looks like your quotes are off here:
['spt.created_at as date_paid']
should be:
['spt.created_at' as 'date_paid']

Get Max value of a DATE and an ID in order to filter results

I'm trying to get the latest "date" so the max value of "date" and from the same table I want the max value of "stand" also from the same ID.
I have tons of dates, stands for one ID but i only want to extract the latest.
im trying to save it into a function i dont know yet if thats the best idea. The rest of my query It's made of inner joins.
Datum is of type date.
stand is decimal(18,6)
DECLARE #MAXDATE DATE
DECLARE #MAXSTAND decimal(18,6)
SELECT #MAXDATE = MAX(Datum) FROM [dbo].[1] WHERE ID = ID
SELECT #MAXSTAND = Stand FROM [dbo].[2]WHERE ID = ID
Result I get: #MAXDATE: 2106-10-13
Result I get: #MAXSTAND: 0.000000
Result I want: #MAXDATE: 2018-01-16
result I want: #MAXSTAND: 1098.000000
Assuming SQL Server 2012 or higher, you can use the first_value window function:
SELECT FIRST_VALUE(Stand) OVER(ORDER BY Datum DESC)
FROM TableName
WHERE Id = #Id
This will return the value of Stand where the Datum column has the latest value for the specific Id.
With the data provided, I don't think you need to do something else :
SELECT MAX(Datum), MAX(Stand)
FROM TableName
WHERE ID = #MyId
edit : You want it by ID, you can do this :
SELECT MAX(Datum), MAX(Stand), ID
FROM TableName
GROUP BY ID

excluding rows from resultset in postgres

This is my result set
i am returning this result set on the base of refid using WHERE refid IN.
Over here, i need to apply a logic without any kind of programming (means SQL query only).
if in result set, i am getting period for particular refid then other rows with the same refid must not returned.
for example, 2667105 having period then myid = 612084598 must not get returned in result set.
according to me this can be achieved using CASE but i have no idea how to use it, i mean that i don't know should i use the CASE statement in SELECT statement or WHERE clause...
EDIT:
This is how it suppose to work,
myid = 612084598 is the default row for refid = 2667105 but if specifically wants the refid for period = 6 then it must return all rows except myid = 612084598
but if i am looking for period = 12, for this period no specific refid present in database.. so for this it must return all rows except first one.. means all rows with the refid which is default one..
Not very clear definition of the problem, but try this:
with cte as (
select
*,
first_value(period) over(partition by refid order by myid) as fv
from test
)
select
myid, refid, period
from cte
where period is not null or fv is null
sql fiddle demo