案例查询中的子查询

时间:2018-11-16 18:47:01

标签: sql subquery case

我正在尝试放置一个case语句,该case语句基于来自2个不同子查询的条件。我的问题是,我无法正常工作。

此SQL子查询给出了我在case语句中使用的计数。

我遇到的错误是:

  

x和y附近的语法不正确。

(这是我的子查询)

Select 'Days=' as Days,
case
when x.yest >=0 then '1 Day'
when y.DayBefore <=3 then '1 Day'
else '2 Day'
end as Days
from
(
Select count(*) as yest 
from
[Main], [DailyStatus]
where Approved_Date is null
Submitted_Date = cast(LAST_WEEKDAY_DATE as date) x,

(
Select count(*) as DayBefore
 from [Main], [DailyStatus]
where Approved_Date is null
and Submitted_Date = dateadd(dd, -1, cast(LAST_WEEKDAY_DATE as date))
)y

下面是我的桌子:

主要 批准日期 提交日期

DailyStatus Last_Weekday_date

我非常感谢您对此提供的任何帮助。 谢谢,Shikha

2 个答案:

答案 0 :(得分:1)

正确缩进您的sql,这将使这些问题更容易发现

Select 
  'Days=' as Days,
  case
    when x.yest >=0 then '1 Day'
    when y.DayBefore <=3 then '1 Day'
    else '2 Day'
  end as Days
from
(
  Select 
    count(*) as yest 
  from
    [Main]
    CROSS JOIN
    [DailyStatus]
  where 
    Approved_Date is nulL AND 
    Submitted_Date = cast(LAST_WEEKDAY_DATE as date) 
) x
CROSS JOIN
(
  Select 
    count(*) as DayBefore
  from 
    [Main]
    CROSS JOIN 
    [DailyStatus]
  where 
    Approved_Date is null and 
    Submitted_Date = dateadd(dd, -1, cast(LAST_WEEKDAY_DATE as date))
)y

大约20年前,像这样进行连接(from table1, table2)也不受欢迎。请使用现代的连接语法

答案 1 :(得分:0)

编辑了语法错误,并进行了一些格式化,使其更易于阅读。 PS-不喜欢您的隐式加入。您应该使用<join type> JOIN .... ON...

来明确
SELECT
      'Days=' AS [Days]
    , CASE
         WHEN [x].[yest] >= 0 THEN '1 Day'
         WHEN [y].[DayBefore] <= 3 THEN '1 Day'
      ELSE '2 Day'
      END AS     [Days]
FROM
    (
        SELECT
             COUNT(*) AS [yest]
        FROM
            [Main]
          , [DailyStatus]
        WHERE  [Approved_Date] IS NULL
             AND [Submitted_Date] = CAST([LAST_WEEKDAY_DATE] AS DATE)
    ) AS [x]
   ,
    (
        SELECT
             COUNT(*) AS [DayBefore]
        FROM
            [Main]
          , [DailyStatus]
        WHERE  [Approved_Date] IS NULL
             AND [Submitted_Date] = DATEADD([dd], -1, CAST([LAST_WEEKDAY_DATE] AS DATE))
    ) AS [y]