我试图在SQL中返回一些值。让我们将Column A
称为UniqueIdentifier
,然后有一行列出了可以针对此唯一标识符执行的两种不同操作,我们将其称为列action
和操作a
, b
每个唯一标识符可以重复执行多次操作,从而列出大量重复的UniqueIdentifier
如何获取执行了操作UniqueIdentifier
的{{1}}的计数和未执行操作a
的计数?
我确实使用临时表创建了一个非常漫长而繁琐的方法(下面列出),但是我觉得必须有一个更round回的方法
a
答案 0 :(得分:0)
您要DISTINCT
吗?
select case when actionflag > 0 then 1 else 0 end [actionflag],
count(distinct uniqueidentifier)
from #actionflagscount
group by case when actionflag > 0 then 1 else 0 end
答案 1 :(得分:0)
这就是我想出的
DROP TABLE IF EXISTS #temp
CREATE TABLE #temp ([UniqueIdentifier] INT, Action NVARCHAR(10))
INSERT INTO #temp ([UniqueIdentifier], Action) VALUES (1, 'a')
INSERT INTO #temp ([UniqueIdentifier], Action) VALUES (2, 'a')
INSERT INTO #temp ([UniqueIdentifier], Action) VALUES (3, 'a')
INSERT INTO #temp ([UniqueIdentifier], Action) VALUES (4, 'b')
INSERT INTO #temp ([UniqueIdentifier], Action) VALUES (5, 'b')
INSERT INTO #temp ([UniqueIdentifier], Action) VALUES (6, 'c')
INSERT INTO #temp ([UniqueIdentifier], Action) VALUES (7, 'c')
SELECT CASE WHEN Action = 'a' THEN 1 ELSE 0 END AS ActionFlag, COUNT(*)
FROM #temp
GROUP BY CASE WHEN Action = 'a' THEN 1 ELSE 0 END
-- Results:
-- ActionFlag (No column name)
-- 0 4
-- 1 3
答案 2 :(得分:0)
考虑到您可能有:
var received_token;
var url = "https://www.googleapis.com/analytics/v3/data/realtime";
var paramsObject = { ids:"ga:123456789"};
const gtoken = new GoogleToken({
keyFile: 'pathToServiceAccountJSONKeyFile:',
scope: ['https://www.googleapis.com/auth/analytics.readonly']
});
gtoken.getToken(function(err, token) {
if (err) {
console.log(err);
return;
}
received_token = token;
console.log(token);
request({
url: url,
qs: paramsObject,
headers: {
'Authorization': received_token
}
}, function(err, response, body) {
if(err) { console.log(err); return; }
// console.log(response);
console.log(body);
});
在同一个action
上执行了几次UniqueIdentifier
上执行的不同action
我会做的:
UniqueIdentifier
如果一切正常,那么简单的SELECT DISTINCT UniqueIdentifier, CASE WHEN EXISTS (SELECT 1 FROM MyDatabase WHERE action = 'a' and UniqueIdentifier = MDB.UniqueIdentifier) THEN 1 ELSE 0 END AS ActionPerformed
FROM MyDatabase MDB
就可以解决上一个查询。
COUNT
SELECT Count(*), ActionPerformed
FROM (
SELECT DISTINCT UniqueIdentifier, CASE WHEN EXISTS (SELECT 1 FROM MyDatabase WHERE action = 'a' and UniqueIdentifier = MDB.UniqueIdentifier) THEN 1 ELSE 0 END AS ActionPerformed
FROM MyDatabase MDB
) T
GROUP BY ActionPerformed
表示执行了ActionPerformed = 1
(可能在同一action
上也执行了action
b)。 UniqueIdentifier
表示未执行ActionPerformed = 0
a(但没有说出action
b))
答案 3 :(得分:0)
我将使用两种聚合级别:
select sum(case when num_as > 0 then 1 else 0 end) as num_with_as,
sum(case when num_as = 0 then 1 else 0 end) as num_without_as
from (select uniqueidentifier,
sum(case when action = 'a' then 1 else 0 end) as num_as
from mydatabase
group by uniqueidentifier
) d;
内部查询计算每个uniqueidentifier
中“ a”的数量。外部查询使用它来获取所需的两个值。