I want to get values of TIMESTAMP and STRING_VALUE based on selected ID.
Suppose My Selected ID is 4259,4226 and 4259
Then It should select TIMESTAMP and STRING_VALUE for selected ID using CASE Statement.
I have tried Below query but returning Into Error
CREATE TABLE "DRL_FTO3_DI1_A0"
(
"VARIABLE" integer,
"CALCULATION" integer,
"TIMESTAMP_S" integer,
"TIMESTAMP_MS" integer,
"VALUE" double precision,
"STATUS" integer,
"GUID" character(36),
"STRVALUE" character varying(50)
)
INSERT INTO "DRL_FTO3_DI1_A0"(
"VARIABLE", "CALCULATION", "TIMESTAMP_S", "TIMESTAMP_MS", "VALUE",
"STATUS", "GUID", "STRVALUE")
VALUES (4226, 0, 1451120925, 329,0 , 1078067200, '', 'BATCH 1'),
(4306, 0, 1451120925, 329,0 , 1078067200, '', 'BATCH 2'),
(4311, 0, 1451120925, 329,0 , 1078067200, '', '2')
Now Suppose Out of three Variable(4226,4306,4311) I want to select 4226 and 4311
SELECT ((TIMESTAMP WITHOUT Time Zone 'epoch' + "TIMESTAMP_S" * INTERVAL '1 second') AT TIME ZONE 'UTC')::TIMESTAMP WITHOUT Time Zone,
SUM(CASE WHEN "VARIABLE" = 4226 Then "STRVALUE" END) as 'A',
SUM(CASE WHEN "VARIABLE" = 4311 Then "STRVALUE" END) as 'B'
FROM "DRL_FTO3_DI1_A0"
GROUP BY "TIMESTAMP_S"
ORDER BY "TIMESTAMP_S";
TIMESTAMP_S A B
2015-12-26 14:38:45 BATCH_1 2
This Is the Query using crosstab and It Works
SELECT *
FROM crosstab (
$$SELECT "VARIABLE", "TIMESTAMP_S", "STRVALUE"
FROM "DRL_FTO3_DI1_A0"
WHERE "VARIABLE" = ANY (array[4306,4226])
ORDER BY 1,2$$
)
AS
t (
"TIMESTAMP_S" integer,
"A" character varying,
"B" character varying
);
Related
I have the below tables:
CREATE SCHEMA pulse;
CREATE TABLE pulse.event(
id integer,
url text,
name text,
event_start date,
event_end date,
sub_type text,
preference jsonb
);
CREATE TABLE pulse.event_meta(
event_id integer,
data json
);
CREATE TABLE pulse.slot_archive(
id integer,
event_id integer,
location_id integer,
date text,
start_time text,
end_time text,
current_registration integer,
preference json
);
CREATE TABLE pulse.event_booking_archive(
id integer,
event_id integer,
slot_id integer,
status text,
data json
);
The below query retrieves the event when the status is canceled (From the event table, preference column) along with additional data from other tables.
Query:
Select
COALESCE((evnt.preference::json #>> '{eventStatus,status}' is not null)::boolean, false) as "eventCancelled",
COALESCE(attendancecount,0) as "attendanceCount",
COALESCE((meta.data ->> 'walkins')::int, 0) as walkins,
COALESCE((meta.data ->> 'attendanceSubmitted')::boolean, false) as "attendanceSubmitted",
meta.data -> 'heroImage' as "heroImage",
meta.data -> 'tileContent' -> 'registrationPage' ->> 'title' as title,
evnt.id as "eventId",
evnt.url as "eventUrl",
evnt.name as name,
evnt.event_start AT TIME ZONE 'America/New_York' as "startTime",
evnt.event_end AT TIME ZONE 'America/New_York' as "endTime",
evnt.sub_type as "subType",
agg_slot.slotDates as slots,
agg_slot.registrationcount as "registrationCount" from pulse.event as evnt
inner join pulse.event_meta meta on evnt.id = meta.event_id
left join (select event_id, COALESCE(sum((data ->> 'attendanceCount')::int),0) as attendancecount from pulse.event_booking_archive where status = 'SUCCESS' group by event_id) as eb
on evnt.id = eb.event_id,
(select event_id, location_id, array_agg(CONCAT_WS(' ', slot.date,slot.start_time,slot.end_time)) as slotDates, sum(current_registration) as registrationCount from pulse.slot_archive as slot
group by slot.event_id, slot.location_id) as agg_slot
where evnt.id = agg_slot.event_id
and evnt.id in (select id from pulse.event where event_end + interval '48h' < now())
and agg_slot.location_id = '3305';
But, I need help in finding out the event whose event location is canceled. i.e All the slots for that particular event location_id in the slot_archive table have "statusMeta": "CS". I'm stuck here. Can someone please assist?
https://www.db-fiddle.com/f/iqxvqrjDrqb8B3tG1xzpHN/14
I rewrote your request to makes it more clear.
So we have :
With booking_archive_success as
(select event_id, COALESCE(sum((data ->> 'attendanceCount')::int),0) as attendancecount
from pulse.event_booking_archive where status = 'SUCCESS'
group by event_id)
, agg_slot as (
select slot.event_id, slot.location_id
, array_agg(CONCAT_WS(' ', slot.date,slot.start_time,slot.end_time)) as slotDates
, sum(slot.current_registration) as registrationCount
, array_agg(slot.preference->'slotStatus'->>'statusMeta') as statuses
from pulse.slot_archive as slot
group by slot.event_id, slot.location_id)
select COALESCE((evnt.preference::json #>> '{eventStatus,status}' is not null)::boolean, false) as "eventCancelled"
, COALESCE(attendancecount,0) as "attendanceCount"
, COALESCE((meta.data ->> 'walkins')::int, 0) as walkins
, COALESCE((meta.data ->> 'attendanceSubmitted')::boolean, false) as "attendanceSubmitted"
, meta.data -> 'heroImage' as "heroImage"
, meta.data -> 'tileContent' -> 'registrationPage' ->> 'title' as title
, evnt.id as "eventId"
, evnt.url as "eventUrl"
, evnt.name as name
, evnt.event_start AT TIME ZONE 'America/New_York' as "startTime"
,evnt.event_end AT TIME ZONE 'America/New_York' as "endTime"
--, evnt.type as type
, evnt.sub_type as "subType"
, agg_slot.slotDates as slots
, agg_slot.registrationcount as "registrationCount"
, agg_slot.statuses
from pulse.event as evnt
inner join pulse.event_meta meta on evnt.id = meta.event_id
left join booking_archive_success as eb on evnt.id = eb.event_id
inner join agg_slot on evnt.id = agg_slot.event_id
where evnt.id in
(select id from pulse.event where event_end + interval '48h' < now())
and not exists (Select 1 from (Select unnest(agg_slot.statuses) as statusMeta from agg_slot a Where a.event_id = evnt.id) t
where statusMeta not like 'CS' or statusMeta is null
)
and agg_slot.location_id = '3305';
Several good habits to take :
Prefer the using of CTE when it is possible. The code is more readable, and easier to conceive
Avoid Cartesian Product in the from with the join condition in the where, so I fixed it by using an inner join clause
To solve (I hope) your problem, I used the unnest function in a "not exists" condition in the where. The goal is to forbid every eventid where one of the statusMeta is not CS
I have a large table that has a structure something like the following:
Create Table public.example
(
id character varying(7) ,
type character varying(1) ,
amount decimal ,
date1 date ,
plan character varying(2) ,
date2 date );
Insert into public.example
( Id,Type,Amount,Date1,Plan,Date2)
values
( '1343657' , 'e',235.26 ,'2021-01-03', 'HS', '2021-07-03'),
( '1343657' , 's',6234.25,'2021-01-15', 'RT', '2021-05-09'),
( '1343657' , 's',235.26 ,'2021-01-05', 'HS', '2021-05-03'),
( '1343657' , '3',235.26 ,'2021-01-05', 'HS', '2021-05-17'),
( '1343657' , 's',235.26 ,'2021-01-05', 'HS', '2021-03-19'),
( '5364324' , 'e',1245.90,'2021-01-17', 'MM', '2021-04-23'),
( '5364324' , '1',5285.88,'2021-01-14', 'MM', '2021-02-28'),
( '5364324' , 'e',1245.10,'2021-01-08', 'VI', '2021-06-30'),
( '5364324' , 'e',7452.05,'2021-01-10', 'DT', '2021-03-07') ;
I need to list the "amount" field across the report in different buckets based on the value of the “Plan” field. I also need to summarize the amount by Id and Type. My method doesn’t work because it adds another required Group BY and I don’t get a summarized amount by Id and Type.
Select id,type,
case When a.plan ='HS' then sum(amount) else 0 end as "HS",
case When a.plan ='RT' then sum(amount) else 0 end as "RT",
case When a.plan ='MM' then sum(amount) else 0 end as "MM",
case When a.plan ='VI' then sum(amount) else 0 end as "VI",
case When a.plan ='DT' then sum(amount) else 0 end as "DT"
from public.example a
where date2>='2021-01-01' and date2<='2021-12-31'
group by 1,2,a.plan
The perfect solution would allow me to add date1 to the Select output as well.
Select OUTPUT
Thx
Having a table and data like this
CREATE TABLE solicitations
(
id SERIAL PRIMARY KEY,
name text
);
CREATE TABLE donations
(
id SERIAL PRIMARY KEY,
solicitation_id integer REFERENCES solicitations, -- can be null
created_at timestamp without time zone NOT NULL DEFAULT (now() at time zone 'utc'),
amount bigint NOT NULL DEFAULT 0
);
INSERT INTO solicitations (name) VALUES
('solicitation1'), ('solicitation2');
INSERT INTO donations (created_at, solicitation_id, amount) VALUES
('2018-06-26', null, 10), ('2018-06-26', 1, 20), ('2018-06-26', 2, 30),
('2018-06-27', null, 10), ('2018-06-27', 1, 20),
('2018-06-28', null, 10), ('2018-06-28', 1, 20), ('2018-06-28', 2, 30);
How to make solicitation id's dynamic in following select statement using only postgres???
SELECT
"created_at"
-- make dynamic this begins
, COALESCE("no_solicitation", 0) AS "no_solicitation"
, COALESCE("1", 0) AS "1"
, COALESCE("2", 0) AS "2"
-- make dynamic this ends
FROM crosstab(
$source_sql$
SELECT
created_at::date as row_id
, COALESCE(solicitation_id::text, 'no_solicitation') as category
, SUM(amount) as value
FROM donations
GROUP BY row_id, category
ORDER BY row_id, category
$source_sql$
, $category_sql$
-- parametrize with ids from here begins
SELECT unnest('{no_solicitation}'::text[] || ARRAY(SELECT DISTINCT id::text FROM solicitations ORDER BY id))
-- parametrize with ids from here ends
$category_sql$
) AS ct (
"created_at" date
-- make dynamic this begins
, "no_solicitation" bigint
, "1" bigint
, "2" bigint
-- make dynamic this ends
)
The select should return data like this
created_at no_solicitation 1 2
____________________________________
2018-06-26 10 20 30
2018-06-27 10 20 0
2018-06-28 10 20 30
The solicitation ids that should parametrize select are the same as in
SELECT unnest('{no_solicitation}'::text[] || ARRAY(SELECT DISTINCT id::text FROM solicitations ORDER BY id))
One can fiddle the code here
I decided to use json, which is much simpler then crosstab
WITH
all_solicitation_ids AS (
SELECT
unnest('{no_solicitation}'::text[] ||
ARRAY(SELECT DISTINCT id::text FROM solicitations ORDER BY id))
AS col
)
, all_days AS (
SELECT
-- TODO: compute days ad hoc, from min created_at day of donations to max created_at day of donations
generate_series('2018-06-26', '2018-06-28', '1 day'::interval)::date
AS col
)
, all_days_and_all_solicitation_ids AS (
SELECT
all_days.col AS created_at
, all_solicitation_ids.col AS solicitation_id
FROM all_days, all_solicitation_ids
ORDER BY all_days.col, all_solicitation_ids.col
)
, donations_ AS (
SELECT
created_at::date as created_at
, COALESCE(solicitation_id::text, 'no_solicitation') as solicitation_id
, SUM(amount) as amount
FROM donations
GROUP BY created_at, solicitation_id
ORDER BY created_at, solicitation_id
)
, donations__ AS (
SELECT
all_days_and_all_solicitation_ids.created_at
, all_days_and_all_solicitation_ids.solicitation_id
, COALESCE(donations_.amount, 0) AS amount
FROM all_days_and_all_solicitation_ids
LEFT JOIN donations_
ON all_days_and_all_solicitation_ids.created_at = donations_.created_at
AND all_days_and_all_solicitation_ids.solicitation_id = donations_.solicitation_id
)
SELECT
jsonb_object_agg(solicitation_id, amount) ||
jsonb_object_agg('date', created_at)
AS data
FROM donations__
GROUP BY created_at
which results
data
______________________________________________________________
{"1": 20, "2": 30, "date": "2018-06-28", "no_solicitation": 10}
{"1": 20, "2": 30, "date": "2018-06-26", "no_solicitation": 10}
{"1": 20, "2": 0, "date": "2018-06-27", "no_solicitation": 10}
Thought its not the same that I requested.
It returns only data column, instead of date, no_solicitation, 1, 2, ...., to do so I need to use json_to_record, but I dont know how to produce its as argument dynamically
I am trying struggling with joining alias named columns. Overall, I want an output with the with date, hour, and the actual and forecasted (most recent before 10am on the previous day) windspeeds.
With the below code I get:
ERROR: column "date" does not exist
LINE xx: ...ast_prep.lat AND meso.lon = forecast_prep.lon AND Date ...
I cannot figure out how to get SQL to join these named columns.
Thanks. And yes, I am a SQL newbie.
with forecast_prep as (
SELECT
date_trunc('day', foretime)::date AS Foredate,
extract(hour from foretime)+1 AS foreHE,
lat,
lon,
windspeed,
max(as_of) AS as_of
FROM weather.forecast
WHERE date_trunc('day', foretime)::date-as_of>= interval '16 hours'
GROUP BY Foredate, foreHE, lat, lon, windspeed)
SELECT
meso.station,
date_trunc('day', meso.timestmp)::date AS Date,
extract(hour from meso.timestmp)+1 AS HE,
CAST(AVG(meso.windspd) as numeric(19,2)) As Actual,
forecast_prep.windspeed,
forecast_prep.as_of
FROM weather.meso
INNER JOIN forecast_prep ON (
meso.lat = forecast_prep.lat AND
meso.lon = forecast_prep.lon AND
Date = Foredate AND ----<<<< Error here
HE = foreHE)
WHERE
(meso.timestmp Between '2016-02-01' And '2016-02-02') AND
(meso.station='KSBN')
GROUP BY meso.station, Date, HE, forecast_prep.windspeed, forecast_prep.as_of
ORDER BY Date, HE ASC
Here are the table structures:
-- Table: weather.forecast
-- DROP TABLE weather.forecast;
CREATE TABLE weather.forecast
(
foretime timestamp without time zone NOT NULL,
as_of timestamp without time zone NOT NULL, -- in UTC
summary text,
precipintensity numeric(8,4),
precipprob numeric(2,2),
temperature numeric(5,2),
apptemp numeric(5,2),
dewpoint numeric(5,2),
humidity numeric(2,2),
windspeed numeric(5,2),
windbearing numeric(4,1),
visibility numeric(5,2),
cloudcover numeric(4,2),
pressure numeric(6,2),
ozone numeric(5,2),
preciptype text,
lat numeric(8,6) NOT NULL,
lon numeric(9,6) NOT NULL,
CONSTRAINT forecast_pkey PRIMARY KEY (foretime, as_of, lat, lon)
-- Table: weather.meso
-- DROP TABLE weather.meso;
CREATE TABLE weather.meso
(
timestmp timestamp without time zone NOT NULL,
station text NOT NULL,
lat numeric NOT NULL,
lon numeric NOT NULL,
tmp numeric,
hum numeric,
windspd numeric,
winddir integer,
dew numeric,
CONSTRAINT meso_pkey PRIMARY KEY (timestmp, station, lat, lon)
'Date' alias can't be seen from there.
You can use few tables after WITH, so I'll advice you to move second select there.
I'm not completly sure about weather.meso table structure but by guesing based on your query, this should work:
WITH
forecast_prep AS (
SELECT
date_trunc('day', foretime) :: DATE AS Foredate,
extract(HOUR FROM foretime) + 1 AS foreHE,
lat,
lon,
max(windspeed) as windspeed,
max(as_of) AS as_of
FROM weather.forecast
WHERE date_trunc('day', foretime) :: DATE - as_of >= INTERVAL '16 hours'
GROUP BY Foredate, foreHE, lat, lon
),
tmp AS (
SELECT
meso.station,
meso.lat,
meso.lon,
meso.timestmp,
date_trunc('day', meso.timestmp) :: DATE AS Date,
extract(HOUR FROM meso.timestmp) + 1 AS HE,
CAST(AVG(meso.windspd) AS NUMERIC(19, 2)) AS Actual
FROM weather.meso
GROUP BY station, lat, lon, timestmp, Date, HE
)
SELECT
tmp.station, tmp.Date, tmp.HE, tmp.Actual, forecast_prep.windspeed, forecast_prep.as_of
FROM tmp
INNER JOIN forecast_prep ON (
tmp.lat = forecast_prep.lat
AND tmp.lon = forecast_prep.lon
AND tmp.Date = forecast_prep.Foredate
AND tmp.HE = forecast_prep.foreHE
)
WHERE
(tmp.timestmp BETWEEN '2016-02-01' AND '2016-02-02')
AND (tmp.station = 'KSBN')
GROUP BY
tmp.station, tmp.Date, tmp.HE, forecast_prep.windspeed, forecast_prep.as_of, tmp.Actual
ORDER BY tmp.Date, tmp.HE ASC;
Like in first example right here https://www.postgresql.org/docs/8.4/static/queries-with.html
I have a table:
ID as int, ParentId as int, FreeFromTerxt as varchar(max), ActiveUntil as DateTime
As an example, within this table I have two records.
1, 100, 'Some text', '2015-11-30 12:10:09.0000000'
2, 100, 'New text', null
What I am trying to do is get the current active record, which in the case above would by record 1. To do that I just select with the following criteria:
ActiveUntil > GETDATE()
This works great, but if I change the first date to 2015-10-30, I need to get the null record as this record will take precedence.
So I changed the code to be:
((ActiveUntil is NULL) OR (ActiveUntil > GETDATE()))
But this does not work.
Here is some example with union:
DECLARE #t TABLE ( d DATETIME )
INSERT INTO #t
VALUES ( NULL ),
( '2015-11-30' )
SELECT TOP 1 *
FROM ( SELECT * , 1 AS ordering
FROM #t
WHERE d > GETDATE()
UNION ALL
SELECT * , 2 AS ordering
FROM #t
WHERE d IS NULL
) t
ORDER BY ordering, d
For 2015-11-30 it returns 2015-11-30. For 2015-10-30 it returns null.
Try like this:
((ActiveUntil is NULL) OR (CONVERT(char(10), ActiveUntil ,126)) > GETDATE())
Refer MSDN for Cast and Convert. The format specifier 126 is for YYYY-MM-DD. Or you can use CAST
((ActiveUntil is NULL) OR (CAST(ActiveUntil as Date) > GETDATE())