我想在Select中执行以下操作:
到目前为止,我有以下内容,但在这种情况下不知道如何获得百分比以及如何正确分组。 有人可以告诉我如何调整它以获得我需要的东西吗?
BEGIN
SET NOCOUNT ON;
SELECT (CASE WHEN A.col3 = A.col2 THEN '1' ELSE '0' END) AS match,
(
SELECT B.col1,
B.col2,
B.col3
FROM LogTable B
WHERE B.Category LIKE '2014-04%'
FOR XML PATH(''), ELEMENTS, TYPE
)
FROM LogTable A
WHERE A.Category LIKE '2014-04%'
GROUP BY CASE WHEN A.col3 = A.col2 THEN '1' ELSE '0' END
FOR XML PATH('comparison'), ELEMENTS, TYPE, ROOT('ranks')
END
非常感谢你提供任何帮助,蒂姆。
答案 0 :(得分:1)
它'有点不同,但我会尝试这样的事情:
SELECT a.col1, a.total_count, b.match_count,
(100*b.match_count/a.total_count) AS match_percentage
FROM (
SELECT col1, COUNT(*) AS total_count
FROM LogTable
WHERE Category LIKE '2014-04%'
GROUP BY col1
) a
JOIN (
SELECT col1, COUNT(*) AS match_count
FROM LogTable
WHERE Category LIKE '2014-04%' AND col2=col3
GROUP BY col1
) b ON a.col1=b.col1
作为替代......这应该给出相同的结果。不确定哪个更有效:
SELECT col1, total_count,
(SELECT COUNT(*)
FROM LogTable
WHERE Category LIKE '2014-04%' AND col1=a.col1 AND col2=col3
) AS match_count,
(100*match_count/total_count) AS match_percentage
FROM (
SELECT col1, COUNT(*) AS total_count
FROM LogTable
WHERE Category LIKE '2014-04%'
GROUP BY col1
) a
但是......注意......我不确定所有引擎都能在用于构建match_percentage列的表达式中直接引用子选择列match_count。