我正在使用 SQLServer 2019,并且有订单表。 Orders 表包含 orderid、userid、country、site、count、price 列。我需要帮助编写查询。详细内容请往下看。
问题: 显示从 2010 年起有多少用户订购了基于国家/地区的 5 条带([1]、[2]、[3]、[4-10]、[10-100])展示一次、两次等
结果示例:
Country 1 2 3 4-10 10-100
---------------------------------------------------------
US 0 0 3 4 5
GB 10 10 8 50 60
NL 20 20 20 100 30
....
我的查询: 我使用了从 1 到 3 的数据透视表,并且得到了正确的结果。但是,我无法在数据透视表中写入十到四和十到一百的范围。
我运行了以下查询;
select * from (
SELECT Country,
count(*) as total,
count as totalpay
FROM [CRM].[dbo].[Orders]
where date like '%2010%'
group by Country,count
) countrytotalcnt
pivot
(
sum(total) for totalpay in ([1],[2],[3],[4-10],[10-100])
)countrytotal;
I have error for below;
Msg 8114, Level 16, State 1, Line 24
Error converting data type nvarchar to int.
Msg 473, Level 16, State 1, Line 24
The incorrect value "4-10" is supplied in the PIVOT operator.
Completion time: 2021-10-13T13:55:47.1067875+03:00
正如我在评论中提到的,在这里使用条件聚合,它比
PIVOT
运算符更通用。
此外,您的
WHERE
将会出错,因为 '%2010%'
无法转换为日期和时间数据类型。如果 WHERE
正在“工作”,则问题出在您的设计上,并且您将日期和时间值存储为基于字符串的数据类型;致命缺陷,需要修复。我在这里进一步讨论这一点:varchar 不是一种适合所有数据类型的。我认为您的数据库没有根本缺陷并且使用日期边界。
我无法对此进行测试,因为我们没有样本数据,但这可能就是您想要的。还要注意 SQL 中的注释(尤其是范围 4-10 和 10-100)。
WITH Counts AS(
SELECT O.Country,
COUNT(*) AS Total
O.[Count] AS TotalPay--COUNT is a reserved word, I suggest against naming your columns this
FROM dbo.Orders O
WHERE [date] >= '20200101'
AND [date] < '20210101'
GROUP BY O.Country)
SELECT C.Country,
SUM(CASE TotalPay WHEN 1 THEN Total END) AS [1],
SUM(CASE TotalPay WHEN 2 THEN Total END) AS [2],
SUM(CASE TotalPay WHEN 3 THEN Total END) AS [3],
SUM(CASE WHEN TotalPay BETWEEN 4 AND 10 THEN Total END) AS [4-10], --note this includes 10
SUM(CASE WHEN TotalPay BETWEEN 10 AND 100 THEN Total END) AS [10-100] --Note this includes 10 again
FROM Counts C
GROUP BY C.Country;