问题描述
备注:我的示例过于简化。实际上,我正在处理一个巨大的查询。但是为了说明问题/错误,让我们求助于苹果和橙子。
我的原始查询如下:
SELECT 'FruitsCount' AS "Type",(SELECT count(id) as Counter,[Name] FROM Fruits group by name FOR JSON PATH) AS "Value"
这将导致类似的结果。我们将此称为 A格式
|---------------------|------------------------------------------------------------------------------|
| Type | Value |
|---------------------|------------------------------------------------------------------------------|
| FruitCount | [{"Counter":2,"Name":"Apple"},{"Counter":3,"Name":"Orange"}] |
|---------------------|------------------------------------------------------------------------------|
但是,现在我想创建一个水果和蔬菜计数的联合。我的查询现在看起来像这样
(SELECT count(id) as Counter,[Name] FROM Fruits group by name
UNION
SELECT count(id) as Counter,[Name] FROM vegetables group by name)
FOR JSON PATH
|---------------------|------------------------------------------------------------------------------|
| JSON_F52E2B61-18A1-11d1-B105-00805F49916B |
|---------------------|------------------------------------------------------------------------------|
| [{"Counter":2,"Name":"Orange"},{"Counter":7,"Name":"Tomato"}] |
|---------------------|------------------------------------------------------------------------------|
但是,我希望它采用以前的格式,其中有一个Type和Value列(格式A)。
我尝试执行以下操作:
SELECT 'FruitsCount' AS "Type",((SELECT count(id) as Counter,[Name] FROM vegetables group by name) FOR JSON PATH) as "Value"
但是,我看到Error 156: Incorrect Syntax near the keyword 'FOR'.
然后我尝试了以下操作:
SELECT 'FruitsAndVegCount' AS "Type",[Name] FROM vegetables group by name FOR JSON PATH) as "Value"
但是,我看到Error 1086: The FOR XML and FOR JSON clauses are invalid in views,inline functions,derived tables,and subqueries when they contain a set operator.
我一直想让“联盟化”查询采用格式A。
更新1:这是所需的输出
|---------------------|------------------------------------------------------------------------------------------------|
| Type | Value |
|---------------------|------------------------------------------------------------------------------------------------|
| FruitAndVegCount | [{"Counter":2,"Name":"Tomato"}] |
|---------------------|------------------------------------------------------------------------------------------------|
目标是仅包含两行(类型,值),其中一行是我指定的值(即FruitAndVegCount),而值是由联合查询创建的ResultSet的JSON。
解决方法
如果我正确理解了这个问题,则可以选择以下语句:
SELECT
[Type] = 'FruitAndVegCount',[Value] = (
SELECT Counter,Name
FROM (
SELECT count(id) as Counter,[Name] FROM Fruits group by name
UNION ALL
SELECT count(id) as Counter,[Name] FROM Vegetables group by name
) t
FOR JSON PATH
)
,
您可以使用两列(类型和值)来完成此操作,如下所示。像这样
select 'FruitAndVegCount' as [Type],(select [Counter],[Name]
from (select count(id) as Counter,[Name] from #Fruits group by [name]
union all
select count(id) as Counter,[Name] from #Vegetables group by [name]) u
for json path) [Value];
输出
Type Value
FruitAndVegCount [{"Counter":2,"Name":"apple"},{"Counter":1,"Name":"pear"},{"Counter":2,"Name":"carrot"},"Name":"kale"},"Name":"lettuce"}]