我正在试图弄清楚如何编写一个计算跨多个列的值的查询,结果表在任何列的每个可能值的每列中都有一个计数。
示例:假设我有 mytable
Source data table:
P1 P2 P3
-----------
a b a
a a a
b b b
a b b
我想要一个计算每列中的a和b的查询,产生类似:
Desired query output:
P1 P2 P3
-------------
a | 3 1 2
b | 1 3 2
我知道我可以使用组轻松地为单个列执行此操作:
select P1, count(*) as mycounts
from mytable
group by P1
但是每个列都可以这样做吗?
我正在使用SQL Server 2008(T-SQL)。在此先感谢您的帮助!
答案 0 :(得分:5)
也许是这样的:
首先是一些测试数据:
DECLARE @tbl TABLE(P1 VARCHAR,P2 VARCHAR,P3 VARCHAR)
INSERT INTO @tbl
SELECT 'a','b','a' UNION ALL
SELECT 'a','a','a' UNION ALL
SELECT 'b','b','b' UNION ALL
SELECT 'a','b','b'
然后像这样的一个支点:
SELECT
*
FROM
(
SELECT 'P1' AS P, P1 AS PValue,P1 AS test FROM @tbl
UNION ALL
SELECT 'P2',P2,P2 FROM @tbl
UNION ALL
SELECT 'P3',P3,P3 FROM @tbl
) AS p
PIVOT
(
COUNT(PValue)
FOR P IN ([P1],[P2],[P3])
) AS pvt
Here是有关pivot和unpivot的更多信息
答案 1 :(得分:0)
可能效率不高但是有效。
;WITH data
AS
(
SELECT 'a' AS p1, 'b' AS p2, 'a' AS p3
UNION ALL
SELECT 'a', 'a','a'
UNION ALL
SELECT 'b','b','b'
UNION ALL
SELECT 'a','b','b'
)
SELECT
p_one.value AS header,
p1,
p2,
p3
FROM (SELECT
p1 AS value,
count(*) AS p1
FROM data d
GROUP BY p1) p_one
left JOIN (SELECT
p2 AS value,
count(*) AS p2
FROM data d
GROUP BY p2) p_two
ON p_two.value = p_one.value
left JOIN (SELECT
p3 AS value,
count(*) AS p3
FROM data d
GROUP BY p3) p_three
ON p_two.value = p_three.value