在相关子查询中查找多个不同的属性

时间:2019-05-09 12:32:43

标签: sql sqlite

我试图了解相关子查询,但无法解决这个问题。我需要列出有关具有多个不同供应商的POS数据的工作簿的所有信息。

我必须在job_id上使用相关的子查询。 我不能使用分组依据或同时使用分组。

DO $$
DECLARE
   -- assign your variables here
   -- [variable_name] [type];
BEGIN
   -- do some code
   -- SELECT 1 INTO [variable] FROM ...
   -- [variable] := [value]
END;
$$ LANGUAGE plpgsql;

我也不能用这个来回答这个问题:

SELECT *
FROM bookjobs a
WHERE EXISTS 
            (SELECT DISTINCT vendor_id 
             FROM pos b 
             WHERE b.job_id = a.job_id);

job_id      cust_id     job_date    descr       jobtype
----------  ----------  ----------  ----------  ----------
002         E05         1990-03-03  BUS REPORT  N
004         A01         1990-01-01  PAMPHLETS   R
005         A01         1989-11-23  GOVT        N
006         D04         1988-07-04  CAMPAIGN    H

SCHEMA

SELECT *
FROM bookjobs a
WHERE EXISTS 
             (SELECT job_id 
              FROM pos b 
              WHERE b.job_id = a.job_id 
              GROUP BY job_id 
              HAVING COUNT(job_id) > 1 );

job_id      cust_id     job_date    descr       jobtype
----------  ----------  ----------  ----------  ----------
002         E05         1990-03-03  BUS REPORT  N
004         A01         1990-01-01  PAMPHLETS   R
005         A01         1989-11-23  GOVT        N

预期结果应该是:

CREATE TABLE pos (
  po_id     CHAR(3) NOT NULL,
  job_id    CHAR(3) NOT NULL,
  po_date   DATE,
  vendor_id CHAR(3),

  PRIMARY KEY (po_id),
  FOREIGN KEY (job_id) REFERENCES bookjobs(job_id)

CREATE TABLE bookjobs (
  job_id   CHAR(3) NOT NULL,
  cust_id  CHAR(3) NOT NULL,
  job_date DATE,
  descr    CHAR(10),
  jobtype  CHAR(1),

  PRIMARY KEY (job_id),
  FOREIGN KEY (cust_id) REFERENCES publishers(cust_id)

2 个答案:

答案 0 :(得分:0)

SELECT *
FROM bookjobs a
WHERE ( SELECT COUNT(1)
          FROM pos b 
         WHERE b.job_id = a.job_id  ) >= 2;

答案 1 :(得分:0)

在按JobId分组的where子句中尝试统计供应商

SELECT
     *
FROM
    BookJobs AS B
WHERE
    EXISTS 
        (
        SELECT 
            P.JobId
            ,Count (Vender)
        FROM 
            Pos P
        WHERE
            P.JobId = B.JobId
        Group By 
            P.JobId
        HAVING 
            Count(Vender) > 1
        )