我环顾四周,但我似乎无法理解逻辑。我认为一个好的回答是here,但就像我说的那样,它没有意义,所以更加具体的解释将非常感激。
所以我想表明每个种族的客户使用信用卡的频率。有不同类型的信用卡,但如果CardID = 1,他们使用现金(因此不等于1个声明)。
我希望按种族分组并显示交易次数,但以百分比表示。
Ethnicity | CardUseCount
0 | 100
1 | 200
2 | 300
3 | 400
例如,这就是它的结果:
Ethnicity | CardUsePer
0 | 0.1
1 | 0.2
2 | 0.3
3 | 0.4
但我想这样:
{{1}}
答案 0 :(得分:1)
如果您需要每个种族的卡交易百分比,您必须将每个种族的卡交易除以同一种族的总交易。您不需要子查询:
SELECT Ethnicity, sum(IIF(CardID=1,0,1))/count(1) AS CardUsePercentage
FROM TransactionT
INNER JOIN CustomerT
ON TransactionT.CustomerID = CustomerT.CustomerID
GROUP BY Ethnicity
答案 1 :(得分:0)
从您发布的示例结果发给我看起来您只想将计数除以1000
SELECT Ethnicity,
COUNT(distinctCard.TransactionID) / 1000 AS CardUseCount
FROM <rest part of query>
答案 2 :(得分:0)
我认为您发布的答案就是答案。正如他们在您的评论中所说,您只计算交易,您需要将其除以总交易数。如答案中所述,您需要将计数(...)除以总数。这将按如下方式完成:
SELECT Ethnicity, COUNT(distinctCard.TransactionID)/(SELECT COUNT(TransactionT.TransactionID)
FROM TransactionT WHERE CardID <> 1)
AS CardUsePercent
FROM (SELECT DISTINCT TransactionID, CustomerID FROM TransactionT WHERE CardID <> 1)
AS distinctCard INNER JOIN CustomerT ON distinctCard.CustomerID = CustomerT.CustomerID
GROUP BY Ethnicity
ORDER BY COUNT(distinctCard.TransactionID) ASC
这将给出你想要的结果。
编辑:这可能是错的,因为我不知道你的表的确切格式,但我假设表中的TransactionID字段是唯一的。否则,请使用DISTINCT关键字或表格的PK,具体取决于您的实际实施情况
答案 3 :(得分:0)
SELECT Ethnicity, COUNT(distinctCard.TransactionID) / (SELECT COUNT(1) FROM TransactionT WHERE CardID <> 1) AS CardUsePer
FROM (SELECT DISTINCT TransactionID, CustomerID FROM TransactionT WHERE CardID <> 1)
AS distinctCard INNER JOIN CustomerT ON distinctCard.CustomerID = CustomerT.CustomerID
GROUP BY Ethnicity
ORDER BY COUNT(distinctCard.TransactionID) ASC