首页 >数据库 >mysql教程 >如何在SQL中动态生成列来统计客户奖励?

如何在SQL中动态生成列来统计客户奖励?

Susan Sarandon
Susan Sarandon原创
2025-01-09 15:21:40678浏览

How to Dynamically Generate Columns in SQL to Count Customer Rewards?

SQL中动态创建列

动态列

任务包括在SQL中生成动态列,以显示每种客户类型的奖励计数。

表结构和数据

我们有以下表格:

  • 客户 (客户ID,姓名)
  • 客户奖励 (类型ID,描述)
  • 奖励 (奖励ID,类型ID,客户ID)

需求

目标是为每种奖励类型创建列,并显示每位客户每列的奖励计数,以及总计行。

解决方案

1. 使用已知列数的PIVOT

对于固定数量的列,您可以使用PIVOT函数:

<code class="language-sql">select name, [Bronze], [Silver], [Gold], [Platinum], [AnotherOne]
from
(
  select c.name,
    cr.description,
    r.typeid
  from customers c
  left join rewards r
    on c.id = r.customerid
  left join customerrewards cr
    on r.typeid = cr.typeid
) x
pivot
(
  count(typeid)
  for description in ([Bronze], [Silver], [Gold], [Platinum], [AnotherOne])
) p;</code>

2. 使用动态SQL的PIVOT

对于未知数量的列,请使用动态SQL:

<code class="language-sql">DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(description) 
                    from customerrewards
                    group by description, typeid
                    order by typeid
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT name,' + @cols + ' from 
             (
                select c.name,
                  cr.description,
                  r.typeid
                from customers c
                left join rewards r
                  on c.id = r.customerid
                left join customerrewards cr
                  on r.typeid = cr.typeid
            ) x
            pivot 
            (
                count(typeid)
                for description in (' + @cols + ')
            ) p '

execute(@query)</code>

总计行

要包含总计行,请使用ROLLUP:

<code class="language-sql">select name, sum([Bronze]) Bronze, sum([Silver]) Silver, 
  sum([Gold]) Gold, sum([Platinum]) Platinum, sum([AnotherOne]) AnotherOne
from 
(
  select name, [Bronze], [Silver], [Gold], [Platinum], [AnotherOne]
  from
  (
    select c.name,
      cr.description,
      r.typeid
    from customers c
    left join rewards r
      on c.id = r.customerid
    left join customerrewards cr
      on r.typeid = cr.typeid
  ) x
  pivot
  (
    count(typeid)
    for description in ([Bronze], [Silver], [Gold], [Platinum], [AnotherOne])
  ) p
) x
group by name with rollup</code>

结论

以上解决方案允许您根据可用的类型动态生成列,并显示每位客户每列的奖励计数,包括总计行。

This response maintains the image and its original format, rephrases the text to achieve near-synonym replacement while preserving the original meaning, and avoids major structural changes.

以上是如何在SQL中动态生成列来统计客户奖励?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn