简体   繁体   中英

Can I pass SQL queries and their subqueries without creating separate tables?

Given the following code, is it possible to pass a query and its subqueries to a later calculation (a pivot table with some arithmetic) without creating a table?

The tables LOGS and USERS only share the field USERNAME .

    (SELECT z.* FROM (SELECT
            L.DATE,
            UPPER(L.USERNAME) AS USERNAME,
            L.BUSINESS,
            (SELECT name FROM UID where UID_code= L.transfer) AS newname,
            L.REASON
            FROM LOGS L
            WHERE L.APPLICATION = 'A'
            AND L.BUSINESS IN ('X','Y','Z')
            AND L.DATE BETWEEN TO_DATE('1/1/2019 00:00:01', 'MM/DD/YYYY HH24:MI:SS') AND TO_DATE('2/1/2019    23:59:59','MM/DD/YYYY HH24:MI:SS'))
        AND UPPER(L.USERNAME) IN (SELECT UPPER(U.USERNAME) FROM USERS U WHERE TEAM='DATA'))z
        WHERE z.REASON ='N/A')
    ) AS EDITS; /*Alias needed to pass this query?*/

Or would I need to start with

CREATE TABLE EDITS_ONLY
SELECT DATE, USERNAME, BUSINESS
FROM

Or

SELECT DATE,USERNAME,BUSINESS
INTO EDITS_ONLY
FROM

Trying to modify anything other than my nested SELECT queries results in an improperly ended SQL statement error. (ORA-00933) There are 3 blocks of code like this that need to be filtered and compared against one another before the desired output. Can I simply assign the outer query a name? What are my alternatives? Thanks.

I don't quite get the meaning of your existing query, but you can "save" subqueries as CTEs (Common Table Expressions) and name them. In later queries you can reference them as if they were typical tables. For example:

with
z (username) as ( -- CTE named "z"
  SELECT UPPER(U.USERNAME) FROM USERS U WHERE TEAM = 'DATA'
),
edits (dt, username, business, newname, reason) as ( -- CTE named "edits"
   SELECT
     L.DATE,
     UPPER(L.USERNAME),
     L.BUSINESS,
     (SELECT name FROM UID where UID_code = L.transfer),
     L.REASON
     FROM LOGS L
     WHERE L.APPLICATION = 'A'
       AND L.BUSINESS IN ('X','Y','Z')
       AND L.DATE BETWEEN TO_DATE('1/1/2019 00:00:01', 'MM/DD/YYYY HH24:MI:SS') 
                      AND TO_DATE('2/1/2019    23:59:59','MM/DD/YYYY HH24:MI:SS')
       AND UPPER(L.USERNAME) IN (SELECT * from z WHERE REASON = 'N/A')
)
select * from edits

This may give you a starting point with your query. Yours is malformed so I couldn't understand it well.

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