0

首先:这里是 SQL 新手。不幸的是,我在截止日期前受到了这种压力。:/如果这是一个愚蠢的问题,我深表歉意。

所以我有一个带有不同列的视图的数据库。它有两列我感兴趣:UserIDAge

  • Age以自创建之日起的天数存储报告的年龄。
  • UserID是创建报告的用户。

该视图列出了用户的所有报告。

我们需要做的是从列出每个唯一用户的现有视图中创建一个新表/视图,然后将他们的全部文档分解为不同的年龄组。所以这些列看起来像:

用户 || # rprts <14 天 || # rprts 14-17 天 || # rprts 18-28 天 || # rprts 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,有一种更有效的方法可以做到这一点......)我已经看到了关于使用游标和其他东西的东西,但我不太了解它。

有任何想法吗?

4

2 回答 2

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]
于 2012-08-29T20:30:08.603 回答
0

您可以使用简单的 group by 来执行此操作,使用 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
于 2012-08-29T20:35:13.487 回答