使用case语句在sql查询中创建新列

时间:2018-12-19 18:09:10

标签: sql sql-server case

我做了一些表连接,下面是我的数据外观。

Cust_No Account_No  Product_H_f Product_H_L
123     A9023         Core      Training
123     A9023         Core      Training
834     A9023         Core      Complimentary
634     A9024         Core      Complimentary
264     A9025         DTB       Training
263     A9025         DTB       Complimentary
677     A9025         DTB       Training

我想在此结果中添加一列,称为“接受培训的Customer_no”,应如下所示。 (我的原始查询非常复杂,使用左联接对6个表进行联接)

Cust_No Account_No  Product_H_f Product_H_L Cust_has_Training
123    A9023        Core        Training        Yes
123    A9023        Core        Training        Yes
834    A9023        Core        Complimentary   Yes 
834    A9023        Core        Training        Yes
634    A9024        Core        Complimentary   No
264    A9025        DTB         Training        Yes
263    A9025        DTB         Complimentary   No
677    A9025        DTB         Training        Yes
677    A9025        DTB         Basic           Yes

我正在使用以下代码来实现此目的,并且似乎正在工作。但是由于我有4800万条记录,因此要花很多时间才能运行。有什么方法可以优化此查询?

SELECT Cust_No, 
       Account_No,  
       Product_H_f, 
       Product_H_L,
(CASE WHEN Cust_No IN (SELECT distinct(Cust_No) from table where 
Product_H_L='Training') then 'Yes' else 'No' end) as 'Cust_has_Training'
FROM TABLE 

3 个答案:

答案 0 :(得分:1)

EXISTS可以很好地实现此目的,就像子查询联接一样。如果不提供很多更多的信息,您可能不会比通用的“通常更快”更好。

SELECT Cust_No, 
       Account_No,  
       Product_H_f, 
       Product_H_L,
(CASE WHEN Cust_has_Training.[Cust_No] is not null then 'Yes' else 'No' end) as 'Cust_has_Training'
FROM TABLE 
LEFT JOIN (
   SELECT distinct(Cust_No) AS [Cust_No]
   from table where 
   Product_H_L='Training'
) Cust_has_Training ON Cust_has_Training.[Cust_No]=Table.[Cust_No]

答案 1 :(得分:1)

如何使用EXISTS()

SELECT Cust_No, 
       Account_No,  
       Product_H_f, 
       Product_H_L,
(CASE WHEN EXISTS(SELECT 1 FROM TABLE WHERE Cust_No = T1.Cust_No AND
Product_H_L='Training') then 'Yes' else 'No' end) as 'Cust_has_Training'
FROM TABLE T1

答案 2 :(得分:1)

如果您有一个复杂的查询,那么添加此新计算的最有效(最简单)的方法可能是基于 Windowed Aggregates

private static void CopyDirectory(string source, string destination)
{
    var sourceDir = new DirectoryInfo(source);
    if (!sourceDir.Exists) throw new DirectoryNotFoundException(nameof(source));

    // Add last directory of source to destination and create it
    destination = Path.Combine(destination, sourceDir.Name);
    Directory.CreateDirectory(destination);

    // Copy files from source to destination
    foreach (var file in sourceDir.GetFiles())
    {
        file.CopyTo(Path.Combine(destination, file.Name));
    }

    // Recursively copy sub directories from source to destination
    foreach (var subDir in sourceDir.GetDirectories())
    {
        CopyDirectory(subDir.FullName, destination);
    }
}