UNION ALL - 防止列的组合

时间:2016-07-01 10:56:03

标签: sql sql-server sql-server-2008 sql-server-2005

我尝试了以下操作,但我最终得到了包含来自Amount1的SUM的单个列Amount2。

SELECT 
    YEAR(createdDate) as Year, 
    MONTH(createdDate) AS Month, 
    Sum(GrandTotal) AS Amount1
FROM 
    Quotes
WHERE createdDate BETWEEN @DateFrom AND @DateTo
GROUP BY YEAR(createdDate), MONTH(createdDate)
--ORDER BY YEAR(createdDate), MONTH(createdDate)

UNION ALL

SELECT 
    YEAR(createdDate) as Year, 
    MONTH(createdDate) AS Month, 
    Sum(GrandTotal) AS Amount2
FROM 
    Quotes
WHERE createdDate BETWEEN @DateFrom AND @DateTo
AND orderDate IS NOT NULL
GROUP BY YEAR(createdDate), MONTH(createdDate)
ORDER BY YEAR(createdDate), MONTH(createdDate);

但是我想同时保留Amount1和Amount2列/金额。

实际上我想最终得到以下内容:

Year | Month | Amount1 | Amount2
---------------------------------
2016    4        120       70
2016    5        300       110

2 个答案:

答案 0 :(得分:1)

最简单的方法就是使用条件聚合:

SELECT YEAR(createdDate) as Year, 
       MONTH(createdDate) AS Month, 
       Sum(GrandTotal) AS Amount1,
       SUM(CASE WHEN orderDate IS NOT NULL THEN GrandTotal END) as Amount2
FROM Quotes
WHERE createdDate BETWEEN @DateFrom AND @DateTo
GROUP BY YEAR(createdDate), MONTH(createdDate)
ORDER BY YEAR(createdDate), MONTH(createdDate);

如果您希望单独行(而不是单独的列)中的值,则将键添加到GROUP BY

SELECT YEAR(createdDate) as Year, 
       MONTH(createdDate) AS Month, 
       (CASE WHEN orderDate IS NOT NULL THEN 'valid' ELSE 'null' END) as HasOrderDate,
       Sum(GrandTotal) AS Amount
FROM Quotes
WHERE createdDate BETWEEN @DateFrom AND @DateTo
GROUP BY YEAR(createdDate), MONTH(createdDate),
          (CASE WHEN orderDate IS NOT NULL THEN 'valid' ELSE 'null' END)
ORDER BY YEAR(createdDate), MONTH(createdDate),
         (CASE WHEN orderDate IS NOT NULL THEN 'valid' ELSE 'null' END);

答案 1 :(得分:0)

你不能为Amount1和Amount2获得两列..你的结果是由同一列组成的

列别名应该相同(并且仅在第一个选择中)

SELECT 
    YEAR(createdDate) as Year, 
    MONTH(createdDate) AS Month, 
    Sum(GrandTotal) AS Amount1
FROM 
    Quotes
WHERE createdDate BETWEEN @DateFrom AND @DateTo
GROUP BY YEAR(createdDate), MONTH(createdDate)
--ORDER BY YEAR(createdDate), MONTH(createdDate)

UNION ALL

SELECT 
    YEAR(createdDate) , 
    MONTH(createdDate), 
    Sum(GrandTotal) 
FROM 
    Quotes
WHERE createdDate BETWEEN @DateFrom AND @DateTo
AND orderDate IS NOT NULL
GROUP BY YEAR(createdDate), MONTH(createdDate)
ORDER BY YEAR(createdDate), MONTH(createdDate);

或者如果你想要列,你应该使用正确的JOIN

SELECT 
    YEAR(a.createdDate) as Year, 
    MONTH(a.createdDate) AS Month, 
    Sum(a.GrandTotal) AS Amount1,
    Sum(b.GrandTotal) AS Amount2   
FROM  Quotes as a 
INNER JOIN Quotes as b on (YEAR(a.createdDate) as YEAR(b.createdDate) 
                           AND MONTH(a.createdDate) = MONTH(b.createdDate))
WHERE a.createdDate BETWEEN @DateFrom AND @DateTo
GROUP BY YEAR(a.createdDate), MONTH(a.createdDate)
ORDER BY YEAR(createdDate), MONTH(createdDate)