SQL语法SELECT和Sub SELECT和JOIN

问题描述

我有一个SELECT语句(e),它产生一个结果集。我想将结果集减少为仅数据的最新版本,因此我在选择的末尾放置了一个WHERE子句,其内容WHERE e.[Version] = (SELECT MAX(e.[Version]) FROM [dbo].[d_bpcunits])。 然后,我JOIN将另一个(f) LEFT JOIN [dbo].[d_bpc] as f on e.[bu_product_code] = f.idbpc设置为记录集,因为我希望从主表中显示一致的数据,而不是用户输入的不一致的信息。然后,我使用(f)中的许多字段替换(e)中的字段,这将产生我想要的干净数据集。

这是我打算UNION ALL一起使用的4个结果集之一,以便我可以用于大型分析。

我正在运行sql Server 14.0。

我的选择查询如下:

SELECT
e.[bu_product_code] AS ProductCode,f.[bpc_desc] AS Description,NULL AS BPCCountry,f.[bpc_business_nature] AS BusinessNature,e.[bu_year_month] AS YearMonth,f.[bpc_active_ingredient] AS ActiveIngredient,f.[bpc_ai_content] AS AIContent,f.[bpc_formulation_type] AS FormulationType,f.[bpc_brand] AS Brand,f.[bpc_min_pack] AS MinPack,f.[bpc_product_category] AS ProductCategory,e.[bu_entity] AS Entity,e.[bu_ship_to_ctry] AS ShipToCtry,e.[bu_ccy] AS CCY,e.[bu_data_type] AS DataType,NULL AS ProductType,e.[bu_latest] AS Latest,e.[Version] AS Version,e.[bu_account] AS UAccount,e.[bu_entity_code] AS UEntityCode,e.[bu_interco_code] AS UIntercoCode,e.[bu_pic] AS Upic,e.[bu_source] AS USource,e.[bu_sales_rep] AS USalesRep,e.[bu_qty_type] AS UQtyType,e.[bu_amount] AS UAmount
FROM
[dbo].[d_bpcunits] e
LEFT JOIN [dbo].[d_bpc] as f on e.[bu_product_code] = f.idbpc
WHERE e.[Version] = (SELECT MAX(e.[Version]) FROM [dbo].[d_bpcunits])

谢谢您的帮助。

解决方法

我在查询中看到的唯一问题是最后一行

  --SELECT MAX(e.[Version]) FROM [dbo].[d_bpcunits]

需要更改为

    SELECT MAX([Version]) FROM [dbo].[d_bpcunits]

然后查询变为

SELECT
e.[bu_product_code] AS ProductCode,f.[bpc_desc] AS Description,NULL AS BPCCountry,f.[bpc_business_nature] AS BusinessNature,e.[bu_year_month] AS YearMonth,f.[bpc_active_ingredient] AS ActiveIngredient,f.[bpc_ai_content] AS AIContent,f.[bpc_formulation_type] AS FormulationType,f.[bpc_brand] AS Brand,f.[bpc_min_pack] AS MinPack,f.[bpc_product_category] AS ProductCategory,e.[bu_entity] AS Entity,e.[bu_ship_to_ctry] AS ShipToCtry,e.[bu_ccy] AS CCY,e.[bu_data_type] AS DataType,NULL AS ProductType,e.[bu_latest] AS Latest,e.[Version] AS Version,e.[bu_account] AS UAccount,e.[bu_entity_code] AS UEntityCode,e.[bu_interco_code] AS UIntercoCode,e.[bu_pic] AS Upic,e.[bu_source] AS USource,e.[bu_sales_rep] AS USalesRep,e.[bu_qty_type] AS UQtyType,e.[bu_amount] AS UAmount
FROM
[dbo].[d_bpcunits] e
LEFT JOIN [dbo].[d_bpc] as f on e.[bu_product_code] = f.idbpc
WHERE e.[Version] = (SELECT MAX([Version]) FROM [dbo].[d_bpcunits])

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...