Getting "column ambiguously defined" without any join in code - sql

I get "column ambiguously defined" error while trying to execute following script:
INSERT INTO experience (id_, company, start_, end_, usr, position_)
WITH exp_ AS (
SELECT 0, 0, DATE'2013-04-30', NULL, 11, 'CEO' FROM DUAL UNION ALL
SELECT 1, 0, DATE'2011-12-11', DATE'2013-04-30', 9, 'Administrator' FROM DUAL UNION ALL
SELECT 2, 0, DATE'2013-04-30', DATE'2015-10-27', 6, 'Manager' FROM DUAL UNION ALL
SELECT 3, 1, DATE'2014-11-04', NULL, 10, 'CEO' FROM DUAL UNION ALL
SELECT 4, 1, DATE'2017-06-13', NULL, 13, 'CTO' FROM DUAL UNION ALL
SELECT 5, 1, DATE'2010-04-22', DATE'2018-10-22', 1, 'Manager' FROM DUAL UNION ALL
SELECT 6, 1, DATE'2019-08-26', NULL, 2, 'Trainer' FROM DUAL UNION ALL
SELECT 7, 1, DATE'2006-02-27', DATE'2016-11-30', 6, 'Video Creator' FROM DUAL UNION ALL
SELECT 8, 2, DATE'2012-04-30', DATE'2013-11-24', 5, 'CEO' FROM DUAL UNION ALL
SELECT 9, 2, DATE'2013-01-10', NULL, 0, 'CEO' FROM DUAL UNION ALL
SELECT 10, 2, DATE'2010-11-01', DATE'2017-01-01', 7, 'Video Creator' FROM DUAL UNION ALL
SELECT 11, 2, DATE'2010-10-03', DATE'2018-03-01', 8, 'Commentator' FROM DUAL
)
SELECT * FROM exp_;
I don't use any JOIN here, and the error description says, that it's caused by trying to join two tables with overlapping column's names.
So why I got it here and how to fix it?

This syntax would work only if you drop the CTE and directly insert the rows with UNION ALL:
INSERT INTO experience (id_, company, start_, end_, usr, position_)
SELECT 0, 0, DATE'2013-04-30', NULL, 11, 'CEO' FROM DUAL UNION ALL
SELECT 1, 0, DATE'2011-12-11', DATE'2013-04-30', 9, 'Administrator' FROM DUAL UNION ALL
SELECT 2, 0, DATE'2013-04-30', DATE'2015-10-27', 6, 'Manager' FROM DUAL UNION ALL
SELECT 3, 1, DATE'2014-11-04', NULL, 10, 'CEO' FROM DUAL UNION ALL
SELECT 4, 1, DATE'2017-06-13', NULL, 13, 'CTO' FROM DUAL UNION ALL
SELECT 5, 1, DATE'2010-04-22', DATE'2018-10-22', 1, 'Manager' FROM DUAL UNION ALL
SELECT 6, 1, DATE'2019-08-26', NULL, 2, 'Trainer' FROM DUAL UNION ALL
SELECT 7, 1, DATE'2006-02-27', DATE'2016-11-30', 6, 'Video Creator' FROM DUAL UNION ALL
SELECT 8, 2, DATE'2012-04-30', DATE'2013-11-24', 5, 'CEO' FROM DUAL UNION ALL
SELECT 9, 2, DATE'2013-01-10', NULL, 0, 'CEO' FROM DUAL UNION ALL
SELECT 10, 2, DATE'2010-11-01', DATE'2017-01-01', 7, 'Video Creator' FROM DUAL UNION ALL
SELECT 11, 2, DATE'2010-10-03', DATE'2018-03-01', 8, 'Commentator' FROM DUAL
See the demo.

You columns do not have names in the CTE. Define it with names:
WITH exp_(id_, company, start_, end_, usr, position_) AS (
Here is a db<>fiddle.

You need to give aliases to your columns. It is enough to do it in the first unioned subquery:
INSERT INTO experience (id_, company, start_, end_, usr, position_)
WITH exp_ AS (
SELECT
0 id_,
0 company,
DATE'2013-04-30' start_,
NULL end_,
11 usr,
'CEO' position
FROM DUAL UNION ALL
SELECT 1, 0, DATE'2011-12-11', DATE'2013-04-30', 9, 'Administrator' FROM DUAL UNION ALL
SELECT 2, 0, DATE'2013-04-30', DATE'2015-10-27', 6, 'Manager' FROM DUAL UNION ALL
SELECT 3, 1, DATE'2014-11-04', NULL, 10, 'CEO' FROM DUAL UNION ALL
SELECT 4, 1, DATE'2017-06-13', NULL, 13, 'CTO' FROM DUAL UNION ALL
SELECT 5, 1, DATE'2010-04-22', DATE'2018-10-22', 1, 'Manager' FROM DUAL UNION ALL
SELECT 6, 1, DATE'2019-08-26', NULL, 2, 'Trainer' FROM DUAL UNION ALL
SELECT 7, 1, DATE'2006-02-27', DATE'2016-11-30', 6, 'Video Creator' FROM DUAL UNION ALL
SELECT 8, 2, DATE'2012-04-30', DATE'2013-11-24', 5, 'CEO' FROM DUAL UNION ALL
SELECT 9, 2, DATE'2013-01-10', NULL, 0, 'CEO' FROM DUAL UNION ALL
SELECT 10, 2, DATE'2010-11-01', DATE'2017-01-01', 7, 'Video Creator' FROM DUAL UNION ALL
SELECT 11, 2, DATE'2010-10-03', DATE'2018-03-01', 8, 'Commentator' FROM DUAL
)
SELECT * FROM exp_;
For your use case, you could also consider using the insert all syntax, which avoids the multiple union alls:
insert all
into experience (id_, company, start_, end_, usr, position_)
values(0, 0, date '2013-04-30', null, 11, 'CEO')
into experience (id_, company, start_, end_, usr, position_)
values(1, 0, date '2011-12-11', date '2013-05-30', 9, 'Administrator')
...
select 1 from dual

Related

Find the correct matching record from multiple row using TSQL

I am shredding a XML file which contains different types of questions and their answers. I shredded it into a temp table and but got stuck for TickBox type of questions where the correct answer in different XML node and the options are in different nodes.
As shown in below screenshot, I shredded the XML into the table structure shown.
ID = 560 is TickBoxQuestion and the question you can see under column Value.
This TickBoxQuestion has 5 Multiple options from ID = 541 to 554 and the answer is under NodeName = Text. Note the NodeName = Value(1,2,3,4,5) are the OptionID's for these options which are under NodeName = Text.
The correct answer is listed in ID = 559 and Value = 3 which point to the OptionId under NodeName = Value = 3 so the answer is Value = 'Refinanced by a different adviser at a different firm'
Here is the sample data
CREATE TABLE dbo.Sample1
(
ID int,
ParentName varchar(1000),
ParentPosition int,
depth int,
NodeName varchar(1000),
Value varchar(1000),
FullPath varchar(1000),
XPath varchar(1000)
)
INSERT INTO Sample1 (ID, ParentName, ParentPosition, depth, NodeName, Value, FullPath, XPath)
SELECT 541, 'ListOption', 1, 7, 'Text', 'Term expired and loan paid off in full', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[1]/Text[1]' UNION ALL
SELECT 542, 'ListOption', 1, 7, 'Value', '1', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[1]/Value[1]' UNION ALL
SELECT 544, 'ListOption', 2, 7, 'Text', 'Refinanced by the same adviser', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[2]/Text[1]' UNION ALL
SELECT 545, 'ListOption', 2, 7, 'Value', '2', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[2]/Value[1]' UNION ALL
SELECT 547, 'ListOption', 3, 7, 'Text', 'Refinanced by a different adviser at a different firm', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[3]/Text[1]' UNION ALL
SELECT 548, 'ListOption', 3, 7, 'Value', '3', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[3]/Value[1]' UNION ALL
SELECT 550, 'ListOption', 4, 7, 'Text', 'Repaid early from own funds', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[4]/Text[1]' UNION ALL
SELECT 551, 'ListOption', 4, 7, 'Value', '4', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[4]/Value[1]' UNION ALL
SELECT 553, 'ListOption', 5, 7, 'Text', 'Still Active', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[5]/Text[1]' UNION ALL
SELECT 554, 'ListOption', 5, 7, 'Value', '5', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Options[1]/ListOption[5]/Value[1]' UNION ALL
SELECT 559, 'StringListAnswer', 1, 6, 'string', '3', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/StringListAnswer/string', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/StringListAnswer[1]/string[1]' UNION ALL
SELECT 560, 'TickBoxListQuestion', 1, 5, 'Text', 'What has happened to the loan or mortgage?', 'ArrayOfSection/Section/Elements/TickBoxListQuestion/Text', 'ArrayOfSection[1]/Section[1]/Elements[1]/TickBoxListQuestion[1]/Text[1]' UNION ALL
SELECT 757, 'ListOption', 1, 7, 'Text', 'A director of the Firm', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[1]/Text[1]' UNION ALL
SELECT 758, 'ListOption', 1, 7, 'Value', '1', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[1]/Value[1]' UNION ALL
SELECT 760, 'ListOption', 2, 7, 'Text', 'A manager of the Firm', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[2]/Text[1]' UNION ALL
SELECT 761, 'ListOption', 2, 7, 'Value', '2', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[2]/Value[1]' UNION ALL
SELECT 763, 'ListOption', 3, 7, 'Text', 'Employed/engaged by the Firm', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[3]/Text[1]' UNION ALL
SELECT 764, 'ListOption', 3, 7, 'Value', '3', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[3]/Value[1]' UNION ALL
SELECT 766, 'ListOption', 4, 7, 'Text', 'Directly or indirectly receiving a profit or payment or other benefit from the Firm', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[4]/Text[1]' UNION ALL
SELECT 767, 'ListOption', 4, 7, 'Value', '4', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[4]/Value[1]' UNION ALL
SELECT 769, 'ListOption', 5, 7, 'Text', 'The owner/a part-owner/a shareholder in the Firm or any related entity', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[5]/Text[1]' UNION ALL
SELECT 770, 'ListOption', 5, 7, 'Value', '5', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[5]/Value[1]' UNION ALL
SELECT 772, 'ListOption', 6, 7, 'Text', 'Acting as auditor/appointed actuary of the Firm or for any related entity', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[6]/Text[1]' UNION ALL
SELECT 773, 'ListOption', 6, 7, 'Value', '6', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[6]/Value[1]' UNION ALL
SELECT 775, 'ListOption', 7, 7, 'Text', 'No relation to the Firm', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[7]/Text[1]' UNION ALL
SELECT 776, 'ListOption', 7, 7, 'Value', '7', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Options/ListOption/Value', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Options[1]/ListOption[7]/Value[1]' UNION ALL
SELECT 781, 'StringListAnswer', 1, 6, 'string', '7', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/StringListAnswer/string', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/StringListAnswer[1]/string[1]' UNION ALL
SELECT 782, 'FirmInvolvementTickBoxListQuestion', 1, 5, 'Text', 'With respect to the Firm you are claiming for have you, your spouse or partner or a relative of either of you ever been any of the following?', 'ArrayOfSection/Section/Elements/FirmInvolvementTickBoxListQuestion/Text', 'ArrayOfSection[1]/Section[2]/Elements[1]/FirmInvolvementTickBoxListQuestion[1]/Text[1]'
I want to pivot and get the desired output as shown below
I am using SQL Server 2019.
Thanks

Oracle sql using previous rows data in calculations

I have a table T1 with 06 columns and want to get new two columns using a select query.
Here's T1 with two extra columns (STOCK, WAUC) that i want to get :
CREATE TABLE T1 (MOUVEMENT NUMBER(2), OPERATION VARCHAR2(5), ITEM VARCHAR2(5), INPUT_QTY NUMBER(6, 2), OUTPUT_QTY NUMBER(6, 2), INPUT_PRICE NUMBER(6, 2), STOCK NUMBER(6, 2), WAUC NUMBER(6, 2));
INSERT ALL
INTO T1 VALUES(1, 'I', 'A', 1500, 0, 5, 1500, 5)
INTO T1 VALUES(2, 'I', 'A', 700, 0, 6, 2200, 5.31)
INTO T1 VALUES(3, 'O', 'A', 0, 800, 0, 1400, 5.31)
INTO T1 VALUES(4, 'I', 'A', 1000, 0, 5, 2400, 5.18)
INTO T1 VALUES(5, 'O', 'A', 0, 500, 0, 1900, 5.18)
INTO T1 VALUES(6, 'I', 'A', 1000, 0, 7, 2900, 5.8 )
INTO T1 VALUES(7, 'I', 'A', 2000, 0, 7, 4900, 6.28)
INTO T1 VALUES(8, 'I', 'A', 5000, 0, 7, 5400, 6.34)
INTO T1 VALUES(9, 'O', 'A', 0, 1000, 0, 4400, 6.34)
INTO T1 VALUES(10, 'I','A', 1000, 0, 5, 5400, 6.09)
SELECT 1 FROM DUAL;
WAUC is like weighted average unit cost to valorise our stock.
In case first record : STOCK = INPUT and WAUC = INPUT_PRICE;
In case new INPUT operation : new WAUC should be : (last generated WAUC * last generated stock) + (current INPUT * current INPUT_PRICE)) / current generated STOCK.
Ex for 2nd row : WAUC = ((5 * 1500) + (700 * 6)) / 2200 = 5.31
In case new OUTPUT operation : WAUC should be last generated WAUC.
Ex for 3rd row : WAUC = last generated WAUC (5.31) of the same ITEM A.
Means, WAUC should be changed every new INPUT operation.
In my opinion, STOCK and WAUC should be generated on the fly, not as records,
besause otherwise, only one accidently wrong INPUT_PRICE, will cause wrong next WAUC(s) -> wrong next calculation(s) -> (wrong work).
how can I achieve this?
Thanks in advance.
Your logic is textbook example of need for model clause and can be rewritten to that clause almost as you verbosely specified (note the model clause is a beast, to learn more about it see here or here or here):
with t1 (mouvement, operation, item, input_qty, output_qty, input_price, stock_expected, wauc_expected) as (
select 1, 'I', 'A', 1500, 0, 5, 1500, 5 from dual union all
select 2, 'I', 'A', 700, 0, 6, 2200, 5.31 from dual union all
select 3, 'O', 'A', 0, 800, 0, 1400, 5.31 from dual union all
select 4, 'I', 'A', 1000, 0, 5, 2400, 5.18 from dual union all
select 5, 'O', 'A', 0, 500, 0, 1900, 5.18 from dual union all
select 6, 'I', 'A', 1000, 0, 7, 2900, 5.8 from dual union all
select 7, 'I', 'A', 2000, 0, 7, 4900, 6.28 from dual union all
select 8, 'I', 'A', 500, 0, 7, 5400, 6.34 from dual union all
select 9, 'O', 'A', 0, 1000, 0, 4400, 6.34 from dual union all
select 10, 'I','A', 1000, 0, 5, 5400, 6.09 from dual
)
select * from (
select t1.*, 0 as stock_actual, 0 as wauc_actual from t1
)
model
dimension by (row_number() over (order by mouvement) as rn)
measures (mouvement, operation, item, input_qty, output_qty, input_price, stock_expected, wauc_expected, stock_actual, wauc_actual)
rules (
stock_actual[any] = coalesce(stock_actual[cv(rn) - 1], 0) + case operation[cv(rn)]
when 'I' then input_qty[cv(rn)]
when 'O' then -output_qty[cv(rn)]
end,
wauc_actual[any] = case
when cv(rn) = 1
then input_price[cv(rn)]
when operation[cv(rn)] = 'I'
then trunc((wauc_actual[cv(rn) - 1] * stock_actual[cv(rn) - 1] + input_qty[cv(rn)] * input_price[cv(rn)]) / stock_actual[cv(rn)], 2)
when operation[cv(rn)] = 'O'
then wauc_actual[cv(rn) - 1]
end
)
order by mouvement
(I changed typo in operation=5000->500 for mouvement=8 and added truncation to 2 digits - both I guessed from your expected results.)
Db fiddle here.
Note that simple analytic functions are not sufficient for computation of wauc because they have access only to previous values of column of input dataset, not the values of column being computed by the function itself. For stock it would be possible using running totals of sum(input_qty) over (order by mouvement) - sum(output_qty) over (order by mouvement) but for wauc there is hardly any explicit formula.

Lead and partition function

This is my input table
create table #table1 (id int, FN varchar(20), startdate varchar(20), id1 varchar)
insert #table1
select 1, 'Joe', '2019-01-01', 'A'
union select 1, 'Joe', '2019-01-01', 'B'
union select 1, 'Joe', '2019-01-05', 'C'
union select 1, 'Joe', '2019-01-05', 'D'
union select 1, 'Joe', '2019-01-06', 'E'
union select 2, 'john', '2019-01-05', 'F'
union select 2, 'john', '2019-01-06', 'G'
union select 2, 'john', '2019-01-06', 'H'
union select 2, 'john', '2019-01-07', 'I'
I tried the following code
select *
, dense_rank() OVER (partition by id, fn order by startdate)
, lead(startdate,1) OVER (partition by id, fn order by startdate)
from #table1
order by id
But I require the following output:
I know that there might be a better approach but a least this is a working solution:
select *,
(select MIN(startdate)
from #table1 t1
where t1.id = #table1.id and
t1.fn = #table1.fn and
t1.startdate > #table1.startdate) enddate
from #table1
Result

SQL Query Using AND OR

I have two tables: Customers and Orders.
I need to know which Customers have ordered "Bread" AND (Milk or Ice Cream) in a given month.
How should I write the SQL query?
Thanks.
As others have said in the comments, you should really try to improve your question so that people are more inclined to answer and help you.
Setting up some test data (making assumptions about your schema):
CREATE TABLE Customers (
CustomerID INT,
CustomerName VARCHAR(50)
)
CREATE TABLE Orders (
OrderId INT,
OrderDate DATETIME,
CustomerID INT,
Product VARCHAR(50)
)
INSERT INTO Customers
SELECT 1, 'John Smith'
UNION
SELECT 2, 'Jane Doe'
UNION
SELECT 3, 'Rachel Booth'
UNION
SELECT 4, 'Steve Barnes'
UNION
SELECT 5, 'Nancy Green'
UNION
SELECT 6, 'Phil Jones'
INSERT INTO Orders
SELECT 1, '2016-09-01', 1, 'Bread'
UNION
SELECT 2, '2016-09-10', 3, 'Milk'
UNION
SELECT 3, '2016-09-19', 1, 'Milk'
UNION
SELECT 4, '2016-10-07', 4, 'Bread'
UNION
SELECT 5, '2016-10-13', 2, 'Milk'
UNION
SELECT 6, '2016-10-15', 4, 'Milk'
UNION
SELECT 7, '2016-10-19', 6, 'Milk'
UNION
SELECT 8, '2016-10-21', 6, 'Ice Cream'
UNION
SELECT 9, '2016-10-27', 1, 'Milk'
UNION
SELECT 10, '2016-10-28', 4, 'Milk'
UNION
SELECT 11, '2016-11-06', 5, 'Ice Cream'
UNION
SELECT 12, '2016-11-09', 5, 'Bread'
And setting the desired month to check:
DECLARE #Month DATETIME
SET #Month = '2016-09-01'
I would get a list of Customers fitting your logic like this:
SELECT DISTINCT c.CustomerName
FROM Customers c
JOIN Orders ob ON ob.CustomerID = c.CustomerID
JOIN Orders omi ON omi.CustomerID = c.CustomerID
WHERE ob.Product = 'Bread'
AND omi.Product IN ('Milk','Ice Cream')
AND DATEADD(month, DATEDIFF(month, 0, ob.OrderDate), 0) = DATEADD(month, DATEDIFF(month, 0, omi.OrderDate), 0)
AND DATEADD(month, DATEDIFF(month, 0, ob.OrderDate), 0) = #Month

Query multiple records of a group that has max date....sorta

Example code:
DECLARE #TABLE TABLE (ID int, Name varchar(50), Date Datetime2)
INSERT INTO #TABLE (ID, Name, Date)
SELECT 1, 'abc', GETDATE()
UNION ALL
SELECT 1, 'def', GETDATE()
UNION ALL
SELECT 1, 'hij', GETDATE()
UNION ALL
SELECT 1, 'abc', GETDATE()-2
UNION ALL
SELECT 1, 'def', GETDATE()-2
UNION ALL
SELECT 1, 'hij', GETDATE()-2
UNION ALL
SELECT 1, 'abc', GETDATE()-4
UNION ALL
SELECT 1, 'def', GETDATE()-4
UNION ALL
SELECT 1, 'hij', GETDATE()-4
UNION ALL
SELECT 2, 'abc', GETDATE()-1
UNION ALL
SELECT 2, 'def', GETDATE()-1
UNION ALL
SELECT 2, 'hij', GETDATE()-1
UNION ALL
SELECT 2, 'abc', GETDATE()-3
UNION ALL
SELECT 2, 'def', GETDATE()-3
UNION ALL
SELECT 2, 'hij', GETDATE()-3
UNION ALL
SELECT 2, 'abc', GETDATE()-4
UNION ALL
SELECT 2, 'def', GETDATE()-4
UNION ALL
SELECT 2, 'hij', GETDATE()-4
UNION ALL
SELECT 3, 'abc', GETDATE()+2
UNION ALL
SELECT 3, 'def', GETDATE()+2
UNION ALL
SELECT 3, 'hij', GETDATE()+2
UNION ALL
SELECT 3, 'abc', GETDATE()-4
UNION ALL
SELECT 3, 'def', GETDATE()-4
UNION ALL
SELECT 3, 'hij', GETDATE()-4
UNION ALL
SELECT 3, 'abc', GETDATE()-5
UNION ALL
SELECT 3, 'def', GETDATE()-5
UNION ALL
SELECT 3, 'hij', GETDATE()-5
UNION ALL
SELECT 4, 'abc', GETDATE()+1
UNION ALL
SELECT 4, 'def', GETDATE()+1
UNION ALL
SELECT 4, 'hij', GETDATE()+1
UNION ALL
SELECT 4, 'abc', GETDATE()-4
UNION ALL
SELECT 4, 'def', GETDATE()-4
UNION ALL
SELECT 4, 'hij', GETDATE()-4
UNION ALL
SELECT 4, 'abc', GETDATE()-5
UNION ALL
SELECT 4, 'def', GETDATE()-5
UNION ALL
SELECT 4, 'hij', GETDATE()-5
SELECT * FROM #TABLE
The data output that I want reflects output of the following records
3 abc 2013-09-18
3 def 2013-09-18
3 hij 2013-09-18
Description: I would like to query the data for the ID/Name that was processed most recently (Max(Date)) (there can be multiple ID's if they were processed at the same date/time)
My try...
SELECT DISTINCT A.*, B.My_Rank
FROM #TABLE A
INNER JOIN
(
SELECT DISTINCT ID, Name, CONVERT(varchar(8), Date, 101) AS Date, RANK() OVER (PARTITION BY ID, Name ORDER BY CONVERT(varchar(8), Date, 101) DESC) My_Rank, MAX(CONVERT(varchar(8), Date, 101)) OVER (partition by ID, Name) Max_Date
FROM #TABLE
GROUP BY ID, Name, CONVERT(varchar(8), Date, 101)
) B
ON A.ID = B.ID AND CONVERT(varchar(8), A.Date, 101) = B.Max_Date
WHERE My_Rank = 1
Clearly, this logic is not working out. "I want to get records for ID/Name/Date based on latest processed ID/Name.
Thank you
You were close, but you don't have to join back (and you probably don't want the PARTITION BY id:
SELECT *
FROM
(
SELECT ID, Name, Date,
RANK() OVER (ORDER BY CAST(Date AS DATE) DESC) My_Rank
FROM #TABLE
) dt
WHERE My_rank = 1
AFAIK SS2008 supports CAST(x AS DATE)
You want to use max() with the partition by clause:
SELECT *
FROM (select a.*,
max("date") over (partition by id) as maxdate
from #TABLE A
) a
where "date" = maxdate;
This can return multiple rows. If you only one one, even when there are ties, then use row_number():
SELECT *
FROM (select a.*,
row_number() over (partition by id order by "date" desc) as seqnum
from #TABLE A
) a
where seqnum = 1;