2016-02-07 60 views
2

這是我當前的SQL查詢:上述查詢的如何更改SQL選擇查詢作爲SQL Server CE中的新表?

SELECT 
    SUM(CASE WHEN (DATEDIFF(day, tbl_debit.purchasedate, GETDATE()) >= 45) 
      THEN tbl_invoices.pendingamount ELSE 0 END) AS morethan45, 
    SUM(CASE WHEN (DATEDIFF(day, tbl_debit.purchasedate, GETDATE()) < 45) 
      THEN tbl_invoices.pendingamount ELSE 0 END) AS lessthan45 
FROM 
    tbl_debit 
INNER JOIN 
    tbl_invoices ON tbl_debit.invoice = tbl_invoices.invoice 
WHERE 
    (tbl_invoices.state = - 1) 

輸出如下所示:

morethan45 | lessthan45 
    750   |  710 

我想創建一個新的表像之下。是否有可能在group by創造新的東西像下面

Column 1  | Column 2 
morethan45 | 750 
lessthan45 | 710 

回答

2

相同的查詢可以改變一點來得到結果。

而是根據病情聚集pendingamount的,你可以添加一個新的列來定義範圍和Group by

SELECT CASE 
     WHEN Datediff(day, tbl_debit.purchasedate, Getdate()) >= 45 THEN 'morethan45' 
     ELSE 'lessthan45' 
     END        AS [Column 1], 
     Sum(tbl_invoices.pendingamount) AS [Column 2] 
FROM tbl_debit 
     INNER JOIN tbl_invoices 
       ON tbl_debit.invoice = tbl_invoices.invoice 
WHERE tbl_invoices.state = -1 
GROUP BY CASE 
      WHEN (Datediff(day, tbl_debit.purchasedate, Getdate()) >= 45) THEN 'morethan45' 
      ELSE 'lessthan45' 
      END 
使用
1

使用case

SELECT (CASE WHEN (DATEDIFF(day, tbl_debit.purchasedate, GETDATE()) >= 45) 
      THEN 'MoreThan45' 
      ELSE 'LessThan45' 
     END) as Column1, 
     SUM(tbl_invoices.pendingamount) as Column2 
FROM tbl_debit INNER JOIN 
    tbl_invoices 
    ON tbl_debit.invoice = tbl_invoices.invoice 
WHERE tbl_invoices.state = -1 
GROUP BY (CASE WHEN (DATEDIFF(day, tbl_debit.purchasedate, GETDATE()) >= 45) 
       THEN 'MoreThan45' 
       ELSE 'LessThan45' 
      END); 

使用intoinsert填充表。