Question

I would like to retrieve the data in the following sample.The following SQL will return two records.

SELECT -1 AS NUM
FROM TABLE
WHERE COMP_CODE = 'TEST'
  AND (DETL_REMK = 'Rest Day'
       OR SHFT_CODE = 'WK_PH')
  AND RSRV_DATE_1 IS NOT NULL
  AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO
  AND EMPE_ID = 'TEST'
GROUP BY EMPE_ID,
         RSRV_DATE_1

I would like to show the below.

ORG UNIT          EMPE_ID        FAM_NAME       TMS_TYPE     Qty
-----------------------------------------------------------------
''                 ''              ''            Used         -1
''                 ''              ''            Used         -1

So, I 'm trying to do like that the SQL statement. But I got the error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."

How to construct the right SQL. Please help me. Thanks in advance.

SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE,
       ISNULL(CAST(
                  (SELECT -1 AS NUM
                   FROM TABLE
                   WHERE COMP_CODE = 'TEST'
                     AND (DETL_REMK = 'Rest Day'
                          OR SHFT_CODE = 'WK_PH')
                     AND RSRV_DATE_1 IS NOT NULL
                     AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO
                     AND EMPE_ID = 'TEST'
                   GROUP BY EMPE_ID, RSRV_DATE_1)AS NVARCHAR(MAX)),0) QTY

No correct solution

OTHER TIPS

If you're just hardcoding the values outside the subquery, you don't need a subquery to return the 2 rows, just do this:

SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 AS QTY
FROM TABLE
WHERE COMP_CODE = 'TEST'
  AND (DETL_REMK = 'Rest Day'
       OR SHFT_CODE = 'WK_PH')
  AND RSRV_DATE_1 IS NOT NULL
  AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO
  AND EMPE_ID = 'TEST'
GROUP BY EMPE_ID,
         RSRV_DATE_1

The issue here is you're not referencing any columns from your table, just using it to produce an amount of rows. Please share the full issue and code, as I'm sure there is more to this that what you're asking.

You can try this one instead

SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 as QTY
union all
SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 as QTY

You would need to add Top 1 to your subquery, from the error you are getting, looks like the subquery is returning more than 1 row:

SELECT Top 1 -1 AS NUM
FROM TABLE
WHERE COMP_CODE = 'TEST'
AND (DETL_REMK = 'Rest Day',
OR SHFT_CODE = 'WK_PH')
AND RSRV_DATE_1 IS NOT NULL
AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO
AND EMPE_ID = 'TEST'
GROUP BY EMPE_ID, RSRV_DATE_1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top