我有六种不同的选择语句用于SSRS报告目的。
以下是其中的两个陈述。我需要帮助,了解如何{@ 1}}以及将所有陈述合并为一个。
Union All
答案 0 :(得分:1)
您只能应用一个ORDER BY
子句来影响结果的顺序,并且它必须应用于整个结果集。如果我怀疑您希望顶部查询的所有结果都显示在底部查询的结果之前,则需要在数据中添加另一列以允许这种情况发生:
SELECT A.LBrCode AS BranchCode,
(SELECT B.Name FROM D001003 B WHERE A.LBrCode=B.PBrCode) AS BranchName,
C.PrdCd AS Product,
sum(D.FcyTrnAmt) AS Amount,
1 as ResultSet
FROM D009022 A INNER JOIN D009021 C
ON substring(A.PrdAcctId,1,8)=C.PrdCd
AND A.LBrCode=C.LBrCode
LEFT JOIN D009040 D
ON A.PrdAcctId=D.VcrAcctId
AND substring(D.VcrAcctId,1,8)=C.PrdCd
AND A.LBrCode=D.LBrCode
WHERE A.AcctStat <> 3 AND A.DateOpen>=@FromDate AND A.DateOpen<=@ToDate
AND C.ModuleType=11
AND D.DrCr='D'
AND D.CanceledFlag<>'C'
GROUP BY A.LBrCode, C.PrdCd
--ORDER BY A.LBrCode
UNION ALL
SELECT A.LBrCode AS BranchCode,
(SELECT B.Name FROM D001003 B WHERE A.LBrCode=B.PBrCode) AS BranchName,
C.PrdCd AS Product,
sum(A.ActTotBalFcy) AS Balance,
2
FROM D009022 A INNER JOIN D009021 C
ON substring(A.PrdAcctId,1,8)=C.PrdCd
AND A.LBrCode=C.LBrCode
WHERE C.ModuleType=11
AND A.AcctStat <> 3
AND A.DateOpen>=@FromDate AND A.DateOpen<=@ToDate
GROUP BY A.LBrCode, C.PrdCd
ORDER BY ResultSet,BranchCode
答案 1 :(得分:1)
要使联合起作用,两个查询必须具有相同数量的列并且是兼容的数据类型,您可能希望转换列数据类型以确保它们是相同的。例如,您的Amount和Balance列数据类型可能存在问题。
你不能在联合中订购每个单独的语句,这没有意义,因为你将产生一个单独的输出。
但是,考虑到这些要点,您的查询应该按原样运作。
declare @test table (a int, b varchar(10))
insert into @test values (10,'test1')
insert into @test values (20,'test2')
select
a, b
from
@test
UNION ALL
select
a, b
from
@test
order by a
答案 2 :(得分:1)
查看您的查询,我假设您的sum
计算是您所有查询之间的唯一区别。
例如,上面两个union all
查询之间的唯一区别是用于summation
和where
子句过滤器(D.DrCr='D' AND D.CanceledFlag<>'C'
)的字段。如果这是真的,那么您可以使用CASE WHEN
语句来处理所有6种不同的场景:
DECLARE @FromDate AS DATE = '04-Aug-2015';
DECLARE @ToDate AS DATE = '05-Aug-2015';
SELECT A.LBrCode AS BranchCode
,(
SELECT B.NAME
FROM D001003 B
WHERE A.LBrCode = B.PBrCode
) AS BranchName
,C.PrdCd AS Product
,CASE
WHEN D.DrCr = 'D' AND D.CanceledFlag <> 'C'
THEN sum(A.ActTotBalFcy)
/*add other remaining conditions here */
ELSE sum(D.FcyTrnAmt)
END AS Amount
FROM D009022 A
INNER JOIN D009021 C ON substring(A.PrdAcctId, 1, 8) = C.PrdCd
AND A.LBrCode = C.LBrCode
LEFT JOIN D009040 D ON A.PrdAcctId = D.VcrAcctId
AND substring(D.VcrAcctId, 1, 8) = C.PrdCd
AND A.LBrCode = D.LBrCode
WHERE A.AcctStat <> 3
AND A.DateOpen >= @FromDate
AND A.DateOpen <= @ToDate
AND C.ModuleType = 11
GROUP BY A.LBrCode
,C.PrdCd
ORDER BY A.LBrCode
答案 3 :(得分:0)
尝试这样的事情
<action android:name="android.bluetooth.adapter.extra.STATE"/>
答案 4 :(得分:0)
然后我会创建2个CTE:
SELECT *
FROM CTE1
UNION ALL
SELECT *
FROM CTE2
GROUP BY ____
ORDER BY ______
执行UNION ALL
时,不能有超过1个GROUP BY和ORDER BY