简体   繁体   English

SQL中子查询的替代方法?

[英]Alternative for sub-query in SQL?

I have query that should return few column results. 我有应该返回一些列结果的查询。 Also there is one requirement where I have to apply additional filter for one of the columns. 还有一个要求,我必须对其中一列应用其他过滤器。 I found solution using sub-query (select inside of the main select) here is example: 我发现使用子查询(在主选择内选择)的解决方案是示例:

SELECT 
   recid,
   price,
   receive_date,
   (SELECT deduction FROM Cost WHERE recid = c.recid AND status = 'Y') AS deduction
FROM Cost c
   INNER JOIN cost_types ct
      c.recid = ct.recid
WHERE cost_year = '2018'

Query above has to pull all records from the Cost table that match cost_type table records and where cost_year is 2018 . 上面的查询必须从Cost表中cost_typecost_type表记录匹配且cost_year2018所有记录。 On top of that I have to filer deduction where status is Y . 最重要的是,我必须申报statusY deduction I'm wondering what other technique I can use for this query? 我想知道我可以使用什么其他技术进行此查询? I know about UNION / UNION ALL but that is more code and seems redundant. 我知道UNION / UNION ALL但这是更多代码,似乎很多余。 If anyone have suggestions or better way to approach this situation please let me know. 如果有人有建议或更好的方法来解决这种情况,请告诉我。 Also, I was wondering if this would be a better fit for Stored Procedure? 另外,我想知道这是否更适合存储过程? Would that be recommended? 会推荐吗?

A JOIN would be the normal method, something like this: JOIN是正常的方法,如下所示:

SELECT c.recid, c.price, c.receive_date,
       cd.deduction
FROM cost c INNER JOIN
     cost_types ct
     ON c.recid = ct.recid LEFT JOIN
     cost cd
     ON cd.recid = c.recid AND cd.status = 'Y'
WHERE c.cost_year = 2018;

This is guessing where the columns are coming from. 这是在猜测列的来源。 Adjust the qualifiers if the columns come from different tables. 如果这些列来自不同的表,请调整限定词。

You can probably also use a window function: 您可能还可以使用窗口函数:

SELECT c.recid, c.price, c.receive_date,
       SUM(CASE WHEN c.status = 'Y' THEN c.deduction END) OVER (PARTITION BY c.recid) as deduction
FROM cost c INNER JOIN
     cost_types ct
     ON c.recid = ct.recid 
WHERE c.cost_year = 2018;

Why not simply use CASE ?: 为什么不简单使用CASE

SELECT recid, price, receive_date,
      (CASE WHEN status = 'Y' THEN deduction END) AS deduction
FROM Cost c INNER JOIN 
     cost_types ct
     ON c.recid = ct.recid 
WHERE cost_year =  2018;

EDIT : I suspect you want something : 编辑:我怀疑你想要一些东西:

SELECT recid, price, receive_date, c1.deduction 
FROM Cost c INNER JOIN 
     cost_types ct
     ON c.recid = ct.recid OUTER APPLY 
     (SELECT TOP (1) c1.*
      FROM  Cost c1
      WHERE c1.recid = c.recid AND c1.status = 'Y'
      ORDER BY ?? -- Use ordering column based on you want deduction 
     ) c1;
WHERE cost_year =  2018;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM