如何从单个表合并多个查询? 这是我当前的查询,但输出错误
SELECT
Employees201MasterFile.Name, CASE WHEN SUM(StockTrans.conv_bal) IS NULL THEN 0 ELSE SUM(StockTrans.conv_bal) END AS 'curMonthBal',
CASE WHEN SUM(StockTrans.conv_bal) IS NULL THEN 0 ELSE SUM(StockTrans.conv_bal) END AS 'prevMonthsBal'
FROM
Employees201MasterFile INNER JOIN
Stocktrans ON Employees201MasterFile.Name = Stocktrans.Customer
WHERE
stocktrans.date >= '12/01/15' AND stocktrans.date <= '12/31/15'
OR stocktrans.date < '12/01/15' AND stocktrans.conv_bal <> 0
GROUP BY Employees201MasterFile.Name
---------------------------------------------------------------
name currentMonthBalance prevMonBal
EMP1 114 114
EMP2 182 182
EMP3 29 29
输出应为
---------------------------------------------------------------
name currentMonthBalance prevMonBal
EMP1 114 366
EMP2 0 182
EMP3 29 0
我想要的输出: 伪查询:
if employee has balance on this month (december 1 - 31, 2015 only), sum all balance for this month ELSE return 0
--> this will be the currentMonthBalance
if employee has previous month balance, sum all previous balance except (december 2015) the selected month ELSE return 0
--> this will be the prevBalance
这可能在SQL Query上吗?
答案 0 :(得分:0)
您可以使用条件聚合执行此操作:
DECLARE @fromMonth AS DATE = '20151201'
SELECT
emf.Name,
SUM(CASE WHEN st.date >= @fromMonth AND st.date < DATEADD(MONTH, 1, @fromMonth) THEN st.conv_val ELSE 0 END) AS [curMonthBal],
SUM(CASE WHEN st.date < @fromMonth THEN st.conv_val ELSE 0 END) AS [prevMonthsBal]
FROM Employees201MasterFile AS emf
INNER JOIN Stocktrans AS st
ON emf.Name = st.Customer
WHERE
st.date < DATEADD(MONTH, 1, @fromMonth)
GROUP BY emf.Name
您应该在表上使用有意义的别名,以便于阅读。
答案 1 :(得分:0)
你的查询:
SELECT x.Name, curMonthBal, prevMonthsBal FROM
(
SELECT
Employees201MasterFile.Name, CASE WHEN SUM(StockTrans.conv_bal) IS NULL THEN 0 ELSE SUM(StockTrans.conv_bal) END AS 'curMonthBal'
FROM
Employees201MasterFile INNER JOIN
Stocktrans ON Employees201MasterFile.Name = Stocktrans.Customer
WHERE
stocktrans.date >= '12/01/15' AND stocktrans.date <= '12/31/15'
AND stocktrans.conv_bal <> 0
GROUP BY Employees201MasterFile.Name
) x
INNER JOIN
(
SELECT
Employees201MasterFile.Name,
CASE WHEN SUM(StockTrans.conv_bal) IS NULL THEN 0 ELSE SUM(StockTrans.conv_bal) END AS 'prevMonthsBal'
FROM
Employees201MasterFile INNER JOIN
Stocktrans ON Employees201MasterFile.Name = Stocktrans.Customer
WHERE
stocktrans.date < '12/01/15' AND stocktrans.conv_bal <> 0
GROUP BY Employees201MasterFile.Name
) y
ON x.Name = y.Name