简体   繁体   中英

Is there any way to convert a PostgreSQL statement (aggregate) into MS Access SQL?

Is there any way to convert an aggregate SQL query into MS Access SQL?

A simple example:

Table:

CREATE TABLE testing.testtable
(
  aid serial NOT NULL,
  username text,
  words integer,
  sys_time timestamp with time zone NOT NULL DEFAULT now(),
  CONSTRAINT testtable_pkey PRIMARY KEY (aid)
)

insert into testing.testtable (username, words) values
('bob', 30),
('todd', 20),
('bob', 50),
('todd', 10);

The PostgreSQL statement I want to convert to Access SQL:

with cur as
(
    select testtable.username, AVG(testtable.words) as avgwords
    from testing.testtable
    group by testtable.username
), 
prev as
(
    select testtable.username, AVG(testtable.words) as avgwords
    from testing.testtable
    where testtable.sys_time <  date_trunc('day', NOW() - interval '1 month')
    group by testtable.username
)
    select p.username, c.avgwords - p.avgwords as change
    from prev p, cur c
    where p.username = c.username

First, I would rewrite the Postgres query using conditional aggregation as:

select tt.username,
       avg(tt.words) - avg(case when tt.sys_time <  date_trunc('day', NOW() - interval '1 month') then tt.words end)
from testing.testtable tt
group by tt.username

You can do almost the same thing in MS Access. Sort of:

select tt.username,
       avg(tt.words) - avg(iif(tt.sys_time < dateadd("m", -1, date()), tt.words, NULL)
from testing.testtable as tt
group by tt.username;

I don't think that MS Access does integer averages of integers. If so, you might want to convert the words field to a decimal value before the avg() .

However, I encourage you to continue using Postgres.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM