有人可以建议我查询以获得2列的合并计数。我的具体要求如下:
A B Permission
--------------------------
1 2 accept
2 3 accept
3 4 accept
1 6 accept
1 4 accept
2 1 accept
3 1 accept
4 1 pending
我希望计数为1是否属于A
或B
且权限为“accept
”。对于上面的示例,我需要输出为5
答案 0 :(得分:1)
您可以通过使用UNION ALL
首先对数据进行非规范化,然后使用COUNT
来实现所需的结果来实现此目的:
WITH SampleData(A, B, Permission) AS(
SELECT 1, 2, 'accept' UNION ALL
SELECT 2, 3, 'accept' UNION ALL
SELECT 3, 4, 'accept' UNION ALL
SELECT 1, 6, 'accept' UNION ALL
SELECT 1, 4, 'accept' UNION ALL
SELECT 2, 1, 'accept' UNION ALL
SELECT 3, 1, 'accept' UNION ALL
SELECT 4, 1, 'pending'
)
SELECT
t.ColValue,
ValueCount = COUNT(*)
FROM (
SELECT
Col = 'A', ColValue = A, Permission
FROM SampleData
UNION ALL
SELECT
Col = 'B', ColValue = B, Permission
FROM SampleData
) t
WHERE Permission = 'accept'
GROUP BY t.ColValue
<强> RESULT 强>
ColValue ValueCount
----------- -----------
1 5
2 3
3 3
4 2
6 1
答案 1 :(得分:0)
SELECT COUNT(*) FROM table WHERE (A=1 OR B=1) AND Permission LIKE 'accept'
你是说这个?
答案 2 :(得分:0)
我得到了答案并将其更改为postgre:
WITH SampleData(auid, buid, permission) AS(
SELECT 1, 2, 'accept' UNION ALL
SELECT 2, 3, 'accept' UNION ALL
SELECT 3, 4, 'accept' UNION ALL
SELECT 1, 6, 'accept' UNION ALL
SELECT 1, 4, 'accept' UNION ALL
SELECT 2, 1, 'accept' UNION ALL
SELECT 3, 1, 'accept' UNION ALL
SELECT 4, 1, 'pending')
SELECT t.col, COUNT(*)as count
FROM (
SELECT auid as col, permission FROM SampleData
UNION ALL
SELECT buid as col, permission FROM SampleData
) t
WHERE permission = 'accept'
GROUP BY t.col
<强>结果强>
col count
----------- -----------
1 5
2 3
3 3
4 2
6 1
答案 3 :(得分:0)
正如您所说的A
或B
,我认为当您在A
中有1时,在B
中它意味着1计数;所以我建议这个编辑过的查询?
SELECT M, COUNT(*) As C
FROM (
SELECT A as M, Permission
FROM yourTable
UNION ALL
SELECT B, Permission
FROM yourTable
WHERE A <> B) Dt
WHERE Permission = 'accept'
GROUP BY M