我有一个表App
与应用程序(AppID, RequestDt, OrgID
),一个表Branch
,其名称为分支(branch_id, branch_name
)和Wspace
与员工({ {1}})
branchID, NmbrEmp
此选择将返回:(我只显示两行的例子,实际上有超过1000行)
select
substring(b.RequestDt,1,6) as Date,
a.branch_name,
d.NmbrEmp,
COUNT(b.AppId) as TotalApp,
SUM(convert(int,b.OKFlg)) as TotalAppOK
SUM(convert(int,b.NotOKFlg)) as TotalAppNOK,
from
App b
join
Branch a on a.branch_id = b.OrgId
left join
WSpace d on a.branch_id = d.branchID
where
substring(b.RequestDt,1,6) >= 201301
group by
substring(b.RequestDt,1,6), a.branch_name, d.NmbrEmp
现在我想添加 Date Branch NmbrEmp TotalApp TotalAppOK TotalAppNOK
--------------------------------------------------------------------
201402 Home 5 28 20 8
201402 Office 4 15 8 7
201403 Home 5 24 7 17
201403 Office 4 30 9 21
的下一列。此INFO
位于另一个名为INFO
的表中,该表仅包含特定的应用程序(App2
)
我想要从表App2中INFO为1的count行,并将该数字放入每行的下一列。
但是每次它都会让我的原始群体变得混乱......那是因为在App2中只有" OKApps" (加上有些应用程序根本不在应用程序中)所以当我这样做时:
AppID, INFO
我的NOTOK应用程序将从群组中消失,当我离开加入时,我之前有更多应用程序...
感谢您的帮助
答案 0 :(得分:0)
就像我在评论中所说,您可以像变量一样使用,或者只使用CROSS JOIN
添加:
DECLARE @someTable TABLE ([Date] VARCHAR(10), Branch VARCHAR(10), NmbrEmp INT, TotalApp INT, TotalAppOK INT, TotalAppNOK INT)
INSERT INTO @someTable SELECT '201402', 'Home', 5, 28, 20, 8
INSERT INTO @someTable SELECT '201402', 'Office', 4, 15, 8, 7
INSERT INTO @someTable SELECT '201403', 'Home', 5, 24, 7, 17
INSERT INTO @someTable SELECT '201403', 'Office', 4, 30, 9, 21
DECLARE @App2 TABLE (AppID INT, INFO INT)
INSERT INTO @App2 SELECT 2, 2
INSERT INTO @App2 SELECT 3, 1
INSERT INTO @App2 SELECT 4, 2
---FIRST CHOICE
DECLARE @App2Count INT = (SELECT COUNT(*) FROM @App2 WHERE INFO = 2)
SELECT Date, Branch, NmbrEmp, TotalApp, TotalAppOK, TotalAppNOK, @App2Count as App2
FROM @someTable
---SECOND CHOICE
SELECT Date, Branch, NmbrEmp, TotalApp, TotalAppOK, TotalAppNOK, A.App2 as App2
FROM @someTable sT
CROSS JOIN (SELECT COUNT(*) as App2 FROM @App2 WHERE INFO = 2) as A
答案 1 :(得分:0)
您应该只计算子查询中的Info
并加入:
select substring(b.RequestDt,1,6) as Date,
a.branch_name,
d.NmbrEmp,
COUNT(b.AppId) as TotalApp,
SUM(convert(int,b.OKFlg)) as TotalAppOK
SUM(convert(int,b.NotOKFlg)) as TotalAppNOK,
e.C
from
App b
join Branch a on a.branch_id = b.OrgId
left join WSpace d on a.branch_id = d.branchID
LEFT JOIN
(SELECT COUNT(*) AS C, AppID
FROM App2
WHERE Info = 1
GROUP BY AppId) e
on e.AppId = b.AppId
where
substring(b.RequestDt,1,6) >= 201301
group by
substring(b.RequestDt,1,6), a.branch_name, d.NmbrEmp