我正在尝试构建以下sp:
USE [MarMoniApp]
GO
/****** Object: StoredProcedure [dbo].[Desc_by_date] Script Date: 10/23/2012 09:01:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Desc_by_date]
@DateToSearch varchar(50)
AS
BEGIN
select a.ticker,a.First_T, a.Last_T, a.Size_mln, a.pct_d_vol,a.a_trad,a.coolname,a.recency,b.Analyst
from Order_Desc a
CASE
When a.coolname = 'ELTORO'
then (Inner join MarMoniApp.dbo.Namelist b on a.ticker = b.ticker )
END
where convert(datetime, cast(rtrim(First_T) AS nvarchar)) > DateToSearch
order by CONVERT(DATETIME, cast(rtrim(First_T) AS nvarchar) ) DESC
END
我只想在“coolname”等于eltoro时才进行内连接,但似乎我的语法不正确。
答案 0 :(得分:1)
如何制作两个select语句然后将它们联合起来。
select ... from Order_Desc a
Inner join MarMoniApp.dbo.Namelist b on a.ticker = b.ticker
where a.coolname = 'ELTORO' AND ...
union
select ... from Order_Desc a
where a.coolname != 'ELTORO' AND ...
答案 1 :(得分:1)
您应该使用左外部加入,如下所示:
select a.ticker,a.First_T, a.Last_T, a.Size_mln, a.pct_d_vol,a.a_trad,a.coolname,a.recency,b.Analyst
from Order_Desc a
LEFT OUTER JOIN MarMoniApp.dbo.Namelist b
on a.ticker = b.ticker
**where
(
(a.coolname <> 'ELTORO')
OR
(a.coolname = 'ELTORO' AND a.ticker = b.ticker)
)**
AND convert(datetime, cast(rtrim(First_T) AS nvarchar)) > DateToSearch
order by CONVERT(DATETIME, cast(rtrim(First_T) AS nvarchar) ) DESC
答案 2 :(得分:0)
可能你需要这样的东西:
INNER JOIN
MarMoniApp.dbo.Namelist b
ON
a.coolname = 'ELTORO'
AND a.ticker = b.ticker
基本上 - 你不能做有条件的JOIN。您只能选择要加入的行。
仅当MarMoniApp.dbo.Namelist
使用a.coolname = 'ELTORO'
时才需要LEFT JOIN
表中的列。
另一个选项(即在性能方面是关键)是使用UNION ALL
作为@Turcia suggested(对于没有JOIN
的部分,使用NULL作为额外列的值)。
答案 3 :(得分:0)
免责声明:我主要使用postgres和mysql,所以我不知道CASE语法...但是,我读SQL的方式,我会把“CASE”中的部分写成
WHERE
Inner join MarMoniApp.dbo.Namelist b on a.ticker = b.ticker and a.coolname='ELTORO')
and convert(datetime, cast(rtrim(First_T) AS nvarchar)) > DateToSearch
order by CONVERT(DATETIME, cast(rtrim(First_T) AS nvarchar) ) DESC
(但是对于cource,我可能误解了CASE语法的想法)