被SQL查询困惑

时间:2016-07-22 16:24:06

标签: sql sql-server database sql-server-2008

USE tempdb;
GO

IF OBJECT_ID('tempdb..#demo_data') IS NOT NULL
BEGIN
  DROP TABLE #demo_data;
END;

CREATE TABLE #demo_data 
(
    row_id          INT PRIMARY KEY,
    product         VARCHAR(30) NOT NULL,
    customer        VARCHAR(30) NOT NULL,
    measure         VARCHAR(30) NOT NULL,
    value           NUMERIC(6, 1)   NOT NULL,
    valid_from_day  INT NOT NULL,
    valid_to_day    INT NOT NULL
);

INSERT INTO #demo_data (
    row_id,
    product,
    customer,
    measure,
    value,
    valid_from_day,
    valid_to_day
)
SELECT 1 row_id, 'Widgets' product, 'Tesco' customer, 'Gross Sales Price' measure, 1 value, 20130101 valid_from_day, 20130401 valid_to_day UNION ALL
SELECT 2 row_id, 'Widgets' product, 'Tesco' customer, 'Gross Sales Price' measure, 1.5 value, 20130301 valid_from_day, 20131231 valid_to_day UNION ALL
SELECT 3 row_id, 'Widgets' product, 'Tesco' customer, 'Gross Sales Price' measure, 2 value, 20130401 valid_from_day, 20150101 valid_to_day UNION ALL
SELECT 4 row_id, 'Widgets' product, 'Tesco' customer, 'Distribution Cost' measure, 5 value, 20130101 valid_from_day, 20130401 valid_to_day UNION ALL
SELECT 5 row_id, 'Widgets' product, 'Tesco' customer, 'Distribution Cost' measure, 6 value, 20130301 valid_from_day, 20140401 valid_to_day UNION ALL
SELECT 6 row_id, 'Widgets' product, 'Tesco' customer, 'Distribution Cost' measure, 7 value, 20131231 valid_from_day, 20150101 valid_to_day UNION ALL
SELECT 7 row_id, 'Widgets' product, 'Asda' customer, 'Gross Sales Price' measure, 100 value, 00000000 valid_from_day, 99999999 valid_to_day UNION ALL
SELECT 8 row_id, 'Widgets' product, 'Asda' customer, 'Gross Sales Price' measure, 200 value, 20131231 valid_from_day, 20150101 valid_to_day UNION ALL
SELECT 9 row_id, 'Widgets' product, 'Asda' customer, 'Distribution Cost' measure, 2 value, 20130301 valid_from_day, 20131231 valid_to_day UNION ALL
SELECT 10 row_id, 'Widgets' product, 'Asda' customer, 'Distribution Cost' measure, 3 value, 20140401 valid_from_day, 20150101 valid_to_day;

SELECT
    row_id,
    product,
    customer,
    measure,
    value,
    valid_from_day,
    valid_to_day
FROM
    #demo_data
ORDER BY 1;

编写SQL以识别哪些行具有相同的产品,客户和度量,具有重叠的日期范围

- 例如第1行和第2行具有相同的产品/客户/度量和重叠的日期范围。

我很困惑你如何在表格中进行比较..我对使用连接有一些想法,但它会是内连接还是只是正常连接

2 个答案:

答案 0 :(得分:0)

您正在寻找的术语是self join。它的工作原理如下:

select yourFields
from yourTable t1 join yourTable t2 on t1.something = t2.something
and t1.somethingElse <> t2.somethingElse

答案 1 :(得分:0)

以下查询是否适合您?它是一个内连接,但加入自身

select  t1.*,  t2.row_id, t2.valid_from_day, t2.valid_to_day 
from #demo_data t1
inner join #demo_data t2
on t1.product=t2.product and t1.customer = t2.customer and t1.measure = t2.measure
and (    (t2.valid_from_day > t1.valid_from_day) and (t2.valid_from_day < t1.valid_to_day)
      or (t2.valid_to_day > t1.valid_from_day) and (t2.valid_to_day < t1.valid_to_day)
    )