与 PIVOT 类似,但值不是离散的

发布于 2024-09-11 10:29:57 字数 361 浏览 1 评论 0原文

一个表列出了多个事件,其中每个事件有四个属性(列),称它们为 A、B、C、P 通过

透视来获取包含 A、B、C、P=1、P=2 列的表将很简单P=3 等。

但是,我需要列为 A、B、C、P<1、P<2、P<3 等。

换句话说,如果“简单”方式的一行是 X, Y, Z, 7, 3, 5, 2 那么我实际需要的是 X, Y, Z, 7, 10, 15, 17,因为任何小于 N 的 P 也小于 N+1。

我知道我可以计算值 (X, Y, Z, 7, 10, 15, 17),将它们加载到临时表中,然后进行旋转,但也许有一些简单的东西我的 SQL 天赋无法立即识别?

如果重要的话,结果将最终出现在 SSRS 中。

A table lists multiple events where each event has four attributes (columns), call them A, B, C, P

It would be simpleto pivot to get a table with columns for A, B, C, P=1, P=2, P=3, etc.

However, I need the columns to be A, B, C, P<1, P<2, P<3, etc.

In other words, if a row of the "simple" way were X, Y, Z, 7, 3, 5, 2 then what I actually need is X, Y, Z, 7, 10, 15, 17 because any P less than N is also less than N+1.

I know I can compute the values (X, Y, Z, 7, 10, 15, 17), load them into a temporary table, and pivot that, but maybe there's something simple that my SQL talents don't recognize immediately?

If it matters, the result will end up in SSRS.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

|煩躁 2024-09-18 10:29:57

如果我理解正确的话,那么这应该可行。

SELECT
    A,
    B,
    C,
    SUM(CASE WHEN P < 1 THEN 1 ELSE 0 END) AS P1,
    SUM(CASE WHEN P < 2 THEN 1 ELSE 0 END) AS P2,
    SUM(CASE WHEN P < 3 THEN 1 ELSE 0 END) AS P3,
    SUM(CASE WHEN P < 4 THEN 1 ELSE 0 END) AS P4
FROM
    Events
GROUP BY
    A,
    B,
    C

这不是动态的。例如,如果其中有一行 P=4,那么它不会添加 P<5 的行。它还严格使用 <而不是<=。

If I understand you correctly, then this should work.

SELECT
    A,
    B,
    C,
    SUM(CASE WHEN P < 1 THEN 1 ELSE 0 END) AS P1,
    SUM(CASE WHEN P < 2 THEN 1 ELSE 0 END) AS P2,
    SUM(CASE WHEN P < 3 THEN 1 ELSE 0 END) AS P3,
    SUM(CASE WHEN P < 4 THEN 1 ELSE 0 END) AS P4
FROM
    Events
GROUP BY
    A,
    B,
    C

This is not dynamic. For example, if you have a row in there with P=4 then it will not add a row for P<5. It's also using strictly < and not <=.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文