我有2个像这样的SQL查询
SELECT TOP 100 PERCENT
COUNT(kodeall) AS Total, kodeall, kode, LEFT(kodeall, 1) AS kode1
FROM
dbo.data
WHERE
date BETWEEN '2013/03/01 00:00:00' AND '2013/03/01 23:59:00'
AND (kodeall IS NOT NULL)
GROUP BY
kodeall, kode
ORDER BY
kode1
和结果
Total l kodeall l kode l kode1
2 1a AA 1
5 1d BB 1
2 2a CC 2
6 2d DD 2
1 2e EE 2
3 3a FF 3
2 3c GG 3
1 3f WW 3
查询#2:
SELECT
COUNT(kodeall) AS Sum, LEFT(kodeall, 1) AS kode1
From
dbo.data
WHERE
date BETWEEN '2013/03/01 00:00:00'
AND '2013/03/01 23:59:00'
AND (kodeall IS NOT NULL)
GROUP BY
LEFT(kodeall, 1)
和结果
Sum l kode1 l
7 1
9 2
6 3
如果我想要显示这样的结果
Total l kodeall l kode l kode1 l sum l Percentage
2 1a AA 1 7 28.57 %
5 1d BB 1 7 71.43 %
2 2a CC 2 9 22.22 %
6 2d DD 2 9 66.66 %
1 2e EE 2 9 11.11 %
3 3a FF 3 6 50 %
2 3c GG 3 6 33.33 %
1 3f WW 3 6 16.67 %
sum是在查询A中用kode1计算kodeall。
和百分比=总数/总和* 100 例2/7 * 100
请帮帮我
答案 0 :(得分:0)
SELECT TOP 100 PERCENT
COUNT(kodeall) AS Total,
kodeall, kode,
LEFT(kodeall, 1) AS kode1 ,
sum1,
((Count(kodeall)/sum1 )* 100) As percentage
FROM
dbo.data
INNER JOIN
(SELECT
COUNT(kodeall) AS Sum,
LEFT(kodeall, 1) AS kode1
From
dbo.data
WHERE
date BETWEEN '2013/03/01 00:00:00'
AND '2013/03/01 23:59:00'
AND (kodeall IS NOT NULL)
GROUP BY
LEFT(kodeall, 1)
) temp on temp.kode1 = dbo.data.kode1
WHERE
date BETWEEN '2013/03/01 00:00:00' AND '2013/03/01 23:59:00'
AND (kodeall IS NOT NULL)
GROUP BY
kodeall, kode
ORDER BY
dbo.data.kode1
答案 1 :(得分:0)
这应该非常接近(未经测试)
With cte1 as (
SELECT COUNT(kodeall) AS Total, kodeall, kode, LEFT(kodeall, 1) AS kode1
FROM dbo.data
WHERE date >= '2013/03/01' AND date < '2013/03/02'
AND kodeall IS NOT NULL
GROUP BY kodeall, kode
), cte2 as (
SELECT COUNT(kodeall) AS Sum, LEFT(kodeall, 1) AS kode1
From dbo.data
WHERE date >= '2013/03/01' AND date < '2013/03/02'
AND kodeall IS NOT NULL
GROUP BY LEFT(kodeall, 1)
)
SELECT c1.Total, c1.kodeall, c1.kode, c1.kode1,
c2.sum, c1.Total/c2.sum percentage
FROM cte1 c1
JOIN cte2 c2 ON c1.kode1 = c2.kode1
小心使用BETWEEN
,尤其是日期字段。相反,我会使用大于或小于。
答案 2 :(得分:0)
我认为自己已经非常接近回答了。我以SQL Server作为RDBMS为例。你没有在你的问题中提到RDBMS。
我使用两个CTE(公用表表达式)来保存您的两个查询,然后将它们连接在一起并计算百分比,请注意,您在最终结果中的百分比实际上是一个字符串。
;WITH CTE_TotalKodeall
AS
(
SELECT TOP 100 PERCENT
COUNT(kodeall) AS Total, kodeall, kode, LEFT(kodeall, 1) AS kode1
FROM
dbo.data
WHERE
date BETWEEN '2013/03/01 00:00:00' AND '2013/03/01 23:59:00'
AND (kodeall IS NOT NULL)
GROUP BY
kodeall, kode
ORDER BY
kode1
), CTE_SUMKodeall
AS
(
SELECT
COUNT(kodeall) AS [Sum], LEFT(kodeall, 1) AS kode1
From
dbo.data
WHERE
date BETWEEN '2013/03/01 00:00:00'
AND '2013/03/01 23:59:00'
AND (kodeall IS NOT NULL)
GROUP BY
LEFT(kodeall, 1)
)
SELECT A.Total, A.kodeall, A.kode, A.kode1, B.[sum],
LEFT(cast((A.Total/(B.[SUM]*1.0) *100.0) as varchar(30)),5)+'%' as Percentage
FROM CTE_TotalKodeall A
JOIN CTE_SUMKodeall B
ON A.kode1 = B.kode1