我有一个SELECT语句如下:
select car.car_ID,isnull(#tmpCount.RowCounter,0) AS RowCounter,ISNULL(#tmpNotServiced.DistinctCounter,0) AS DistinctCounter, ISNULL(#tmpNA.NACounter,0) AS NACounter, (isnull(#tmpCount.RowCounter,0) + ISNULL(#tmpNotServiced.DistinctCounter,0) + ISNULL(#tmpNA.NACounter,0)) AS Total, (CASE ISNULL(#tmpNotServiced.DistinctCounter,0) WHEN 0 THEN 'Closed' ELSE 'Open' END) AS Status
from car
left outer join #tmpCount
on car.AUD_ID = #tmpCount.car_ID
left outer join #tmpNotServiced
on car.AUD_ID = #tmpNotServiced.car_ID
LEFT OUTER JOIN #tmpNA
ON car.car_ID = #tmpNA.car_ID
然后存储的proc [p_GetServiced]计算全部打开并全部关闭。
CREATE PROCEDURE [dbo].[p_GetServiced]
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #tmp1
(
car_ID BIGINT,
RowCounter BIGINT,
DistinctCounter BIGINT,
NACounter BIGINT,
Total BIGINT,
[Status] VARCHAR(MAX)
)
CREATE TABLE #tmp2 (car_ServiceDate DATETIME)
INSERT INTO #tmp1
EXEC [p_GetServiceDetail]
SELECT [Status] AS [Serviced], COUNT(*) AS [Status] FROM #tmp1
GROUP BY [Status]
INSERT INTO #tmp2
SELECT car_TargetDate FROM dbo.car
END
GO
我想让它返回'Serviced'和一小部分(2 of of 5),例如:Serviced(2 of 5)或NotServiced(3/5)
注意:2是开放的,5是总行
答案 0 :(得分:1)
INSERT INTO #tmp1
EXEC [p_GetServiceDetail]
DECLARE @TotalRows BIGINT
SELECT @TotalRows = COUNT(*) FROM #tmp1
SELECT [Status] AS [Serviced], COUNT(*) AS [Status], @TotalRows AS [Rows]
FROM #tmp1
GROUP BY [Status]
或者,重新阅读您的问题,我认为更令人满意的方法是使用OVER
条款:
SELECT DISTINCT
Status
+ ' ('
+ CONVERT(VARCHAR, count(*) OVER (PARTITION BY status))
+ ' OF '
+ CONVERT(VARCHAR, count(*) OVER ())
+ ')'
FROM #tmp1
这产生以下结果:
Serviced (1 OF 4)
NotServiced (3 OF 4)
答案 1 :(得分:1)
以下内容应该为您提供两行,包含两列,一列用于关闭,一列用于打开状态,输出格式为您想要的格式。
SELECT '[OPEN]',
CONVERT(NVARCHAR(100), (SELECT COUNT(*) FROM #tmp1 WHERE [Status] = 'OPEN')) +
' of ' + CONVERT(NVARCHAR(100), COUNT(*))
FROM #tmp1
UNION
SELECT '[CLOSED]',
CONVERT(NVARCHAR(100), (SELECT COUNT(*) FROM #tmp1 WHERE [Status] = 'CLOSED')) +
' of ' + CONVERT(NVARCHAR(100), COUNT(*))
FROM #tmp1