动态SQL:如何从3个不同的表中检索数据并计算结果?

时间:2016-03-10 21:38:58

标签: sql sql-server dynamic-sql

我想计算人们在选择字段中选择某个选项的次数(表示为带有网页选项的元素)。

选择字段的名称存储在CodeType表中。

> select [CodeTypeID] from [CodeType] where [Name] = 'Favorite Fruit'

CodetypeID
----------
1000210

我可以通过找到CodytypeID找到CodetypeID - 表来找到选项:

> select [ArtifactID], [Name] from [Code] where [CodetypeID] = '1000210'

ArtifactID   Name
-------------------
1039477     Apple
1039478     Pear
1039479     Banana
1039912     Peach

每个选项字段都有一个单独的表(名为CodeArtifact_XXXX,其中XXXX是上面找到的CodetypeID。通过计算每个选项的行数(由CodeArtifactID标识),我可以看到选择了多少次:

> select
>   count(case when [CodeArtifactID] = '1039477' then 1 else null end) as 'Apple'
>   count(case when [CodeArtifactID] = '1039478' then 1 else null end) as 'Pear'
>   count(case when [CodeArtifactID] = '1039479' then 1 else null end) as 'Banana'
>   count(case when [CodeArtifactID] = '1039477' then 1 else null end) as 'Peach'
> from
>   [CodeArtifact_1000210]

Apple   Pear    Banana    Peach
-------------------------------
12      0       7         4

然而,我必须计算更多选择领域的选择。因此,硬编码所有这些都不是一种选择。

我认为这里唯一的解决方案是使用动态SQL - 我没有经验。有人能给我一个例子,说明我如何计算任何选择领域,选择他们的选项的次数?

我换句话说:只在开头更改选择字段[Name]Favorite Fruit,'婚姻状况','最新文凭'等),应该自动查找并计算选择。

这可能吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以直接执行以下代码..

    Declare
        @CodeName   nVarChar(100),
        @CodeType   nVarChar(100),
        @ColumnName nVarChar(MAX),
        @DynamicSQL nVarChar(MAX);


    Set @CodeName = 'Favorite Fruit';

    Select
       @CodeType = Convert(varChar, [CodetypeID])
    From
       [dbo].[CodeType]
    Where
       [Name] = @CodeName;

    Create Table #tmpCode
        (
            [ArtifactID]    int,
            [Name]          VarChar(100)
        )

Set @DynamicSQL =
    'Insert Into #tmpCode
        Select
            [ArtifactID],
            [Name]
        From
            [dbo].[CodeType]                As ct
                Inner Join  [dbo].[Code]    As cd
                    On ct.[CodetypeID] = cd.[CodetypeID]' +
                'Inner Join [dbo].[CodeArtifact_' + @CodeType + ']  As ca
                    On ca.[CodeArtifactID] = cd.[ArtifactID]
        Where
            ct.[Name] = @CodeName';

Exec(@DynamicSQL);


    Select @ColumnName =
        STUFF((
            Select
                ',' + QUOTENAME([Name])
            From
                #tmpCode
            Group By
                [Name]
        For XML Path(''), Type).value('.', 'nVarChar(MAX)'), 1, 1, '')


    Set @DynamicSQL =
        'Select ' + @ColumnName + ' From
            (Select [ArtifactID], [Name] From #tmpCode) tmp
            Pivot (Count([ArtifactID]) For [Name] In (' + @ColumnName + ')) As pvt ';

    Exec sp_executesql @DynamicSQL;
    -- Exec (@DynamicSQL);


    Drop Table
        #tmpCode