首先关闭:这里总SQL新手。不幸的是,我在截止日期前对我提出了这个要求。 :/如果这是一个愚蠢的问题我很抱歉。
所以我有一个包含各种列的视图的数据库。它有两个我感兴趣的专栏: UserID 和年龄。
该视图列出了用户的所有报告。
我需要做的是从现有视图中创建一个新表/视图,列出每个唯一用户,然后将其总文档分解为各个年龄组。所以列看起来像:
用户|| #rprts< 14天|| #rprts 14-17天|| #rps 18-28天|| #rps 29-44天|| #rprts 45+天
我知道我可以获得我想要的所有用户的集合:
SELECT DISTINCT [UserID] FROM [DB].[dbo].[DB_View]
我可以通过硬编码UserID#来运行以下内容并获取我想要的新表/视图行:
SELECT DISTINCT
[UserID],
(SELECT COUNT(*) FROM [DB].[dbo].[DB_View] WHERE (Age < 14) AND UserID = '9999') AS "Less Than 14 Days",
(SELECT COUNT(*) FROM [DB].[dbo].[DB_View] WHERE (Age BETWEEN 14 AND 17) AND UserID = '9999') AS "14 to 17 Days",
(SELECT COUNT(*) FROM [DB].[dbo].[DB_View] WHERE (Age BETWEEN 18 AND 28) AND UserID = '9999') AS "18 to 28 Days",
(SELECT COUNT(*) FROM [DB].[dbo].[DB_View] WHERE (Age BETWEEN 29 AND 44) AND UserID = '9999') AS "29 to 44 Days",
(SELECT COUNT(*) FROM [DB].[dbo].[DB_View] WHERE (Age >= 45) AND UserID = '9999') AS "Over 45 Days"
FROM [DB].[dbo].[DB_View]
WHERE UserID = '9999'
用户的结果集约为600行,视图通常有大约6,000-15,000行。我最初的想法是获取我的用户结果集,然后将每个用户存储到参数,然后将其传递到我硬编码用户ID的查询中。可悲的是,我甚至无法弄清楚这样做的SQL。 (我猜你有更好的方法可以做到这一点,如果你知道你的SQL ....)我已经看到了使用游标和东西的东西,但我真的不太了解它。
有什么想法吗?
答案 0 :(得分:3)
如果我理解你的话:
SELECT [UserID],
COUNT(CASE WHEN Age < 14 THEN 1 ELSE NULL END) AS [Less Than 14 Days],
COUNT(CASE WHEN Age BETWEEN 14 AND 17 THEN 1 ELSE NULL END) AS [14 to 17 Days],
COUNT(CASE WHEN Age BETWEEN 18 AND 28 THEN 1 ELSE NULL END) AS [18 to 28 Days],
COUNT(CASE WHEN Age BETWEEN 29 AND 44 THEN 1 ELSE NULL END) AS [29 to 44 Days],
COUNT(CASE WHEN Age >= 45 THEN 1 ELSE NULL END) AS [Over 45 Days]
FROM [DB].[dbo].[DB_View]
GROUP BY [UserID]
答案 1 :(得分:0)
您可以使用一个简单的组来执行此操作,使用CASE语句按年龄条件求和:
SELECT [UserID],
SUM(case when Age < 14 then 1 else 0 end) AS "Less Than 14 Days",
SUM(case when Age BETWEEN 14 AND 17 then 1 else 0 end) as "14 to 17 Days",
SUM(case when Age BETWEEN 18 AND 28 then 1 else 0 end) as "18 to 28 Days",
SUM(case when Age BETWEEN 29 AND 44 then 1 else 0 end) as "29 AND 44 Days",
SUM(case when Age BETWEEN 29 AND 44 then 1 else 0 end) as "29 AND 44 Days",
SUM(case when Age >= 45 then 1 else 0 end) as "Over 45 Days"
from [DB].[dbo].[DB_View]
where UserID = '9999'
group by userID