我在理解和使用T-SQL(SQL Server 2012)中的嵌套子查询时遇到了很大的困难:
我可以使用以下查询创建显示EITHER最小值(销售日期)或最大值(销售日期)的表,
'odds'
请帮助。我知道这是一个初学者的问题。
答案 0 :(得分:0)
select * into #fact_invoice_history from
(select 1 as cm_number, 'one' as cm_name, '2018-09-01 10:15:00' as dim_invoice_date
union all select 1, 'one', '2018-09-02 10:15:00'
union all select 1, 'one', '2018-09-03 10:15:00'
union all select 2, 'two', '2018-09-06 10:15:00'
union all select 2, 'two', '2018-09-07 10:15:00'
union all select 3, 'three', '2018-09-08 10:15:00') data
select * from #fact_invoice_history
-- ----------------------------------------
-- cm_number cm_name dim_invoice_date
-- ----------- ------- -------------------
-- 1 one 2018-09-01 10:15:00
-- 1 one 2018-09-02 10:15:00
-- 1 one 2018-09-03 10:15:00
-- 2 two 2018-09-06 10:15:00
-- 2 two 2018-09-07 10:15:00
-- 3 three 2018-09-08 10:15:00
-- ----------------------------------------
select
cm_number,
cm_name,
min(dim_invoice_date) min_sale_date,
max(dim_invoice_date) max_sale_date
from
#fact_invoice_history
group by
cm_number,
cm_name
-- ------------------------------------------------------------
-- cm_number cm_name min_sale_date max_sale_date
-- ----------- ------- ------------------- -------------------
-- 1 one 2018-09-01 10:15:00 2018-09-03 10:15:00
-- 3 three 2018-09-08 10:15:00 2018-09-08 10:15:00
-- 2 two 2018-09-06 10:15:00 2018-09-07 10:15:00
-- ------------------------------------------------------------
drop table #fact_invoice_history
答案 1 :(得分:0)
以下解决方案效果很好。
select
cm_number,
cm_name,
min(dim_invoice_date) min_sale_date,
max(dim_invoice_date) max_sale_date
from
#fact_invoice_history
group by
cm_number,
cm_name
虽然我可能在这里问了一个错误的问题,但感谢您的帮助