How can i get data based on condition from within a group by - sql-server

Consider the following tables
Log (LOG)
Id, CorrId, FlowId, FlowName, AppId, ReqTimestamp, Source, Target, Step, CustomField
Message (MESSAGE)
Id, Url, Method, Headers, MsgBlob, CreatedDatetime
LinkedLogs (LOG_LOGS)
Id, CorrId, LinkedCorId
Create table and insert statements
CREATE TABLE [dbo].[LOG](
[ID] [uniqueidentifier] NOT NULL,
[CORRELATION_ID] [uniqueidentifier] NULL,
[ERROR_CODE] [nvarchar](15) NULL,
[FLOW_ID] [nvarchar](10) NOT NULL,
[APPLICATION_ID] [nvarchar](35) NOT NULL,
[LOG_LEVEL] [nvarchar](35) NOT NULL,
[LOG_TIMESTAMP] [datetime] NOT NULL,
[EVENT_ID] [uniqueidentifier] NOT NULL,
[FLOW_NAME] [nvarchar](50) NOT NULL,
[PROCESS] [nvarchar](256) NOT NULL,
[REQUEST_TIMESTAMP] [datetime] NOT NULL,
[SOURCE] [nvarchar](256) NOT NULL,
[TARGET] [nvarchar](256) NOT NULL,
[STEP] [nvarchar](50) NOT NULL,
[DESCRIPTION] [nvarchar](max) NULL,
[LOG_SEQUENCE] [int] NOT NULL,
[CREATED_DATETIME] [datetime] NOT NULL,
[CUSTOM_FIELD] [nvarchar](60) NULL)
CREATE TABLE [dbo].[MESSAGE](
[ID] [uniqueidentifier] NOT NULL,
[URL] [nvarchar](256) NULL,
[METHOD] [nvarchar](35) NULL,
[MSGBLOB] [varchar](max) NULL,
[HEADERS] [nvarchar](max) NULL,
[CREATED_DATETIME] [datetime] NOT NULL)
CREATE TABLE [dbo].[LOG_LOGS](
[CorrelationId] [uniqueidentifier] NOT NULL,
[LinkedCorrelationId] [uniqueidentifier] NOT NULL,
[CreatedDatetime] [datetime] NULL)
--Log
INSERT [dbo].[LOG]
([ID], [CORRELATION_ID], [ERROR_CODE], [FLOW_ID], [APPLICATION_ID], [LOG_LEVEL], [LOG_TIMESTAMP], [EVENT_ID], [FLOW_NAME], [PROCESS], [REQUEST_TIMESTAMP], [SOURCE], [TARGET], [STEP], [DESCRIPTION], [LOG_SEQUENCE], [CREATED_DATETIME], [CUSTOM_FIELD])
VALUES
('C56BBFBE-5308-4242-ACD0-383F016C0AD1', '8C519F41-1F06-41E5-9647-25554315E1C7', 'NULL', 'TRIGGER', 'appIdString', 'DEBUG', '2019-04-26 14:08:23.660', 'C0F40CA0-682C-11E9-AB6D-0298370A6804', 'trigger', 'imp-trigger', '2019-04-26 14:08:23.660', 'SomeSource', 'SomeTarget', 'START', 'Some description', '1', '2019-04-26 14:08:24.677', 'NULL');
INSERT [dbo].[LOG]
([ID], [CORRELATION_ID], [ERROR_CODE], [FLOW_ID], [APPLICATION_ID], [LOG_LEVEL], [LOG_TIMESTAMP], [EVENT_ID], [FLOW_NAME], [PROCESS], [REQUEST_TIMESTAMP], [SOURCE], [TARGET], [STEP], [DESCRIPTION], [LOG_SEQUENCE], [CREATED_DATETIME], [CUSTOM_FIELD])
VALUES
('273F4E0A-CA7A-40B5-AF54-F2A53A776541', '8C519F41-1F06-41E5-9647-25554315E1C7', 'NULL', 'TRIGGER', 'appIdString', 'DEBUG', '2019-04-26 14:08:25.693', 'C0F40CA0-682C-11E9-AB6D-0298370A6804', 'trigger-melto', 'imp-trigger', '2019-04-26 14:08:23.660', 'SomeSource', 'SomeTarget', 'OUTBOUND', 'Some description', '4', '2019-04-26 14:08:29.110', 'NULL');
INSERT [dbo].[LOG]
([ID], [CORRELATION_ID], [ERROR_CODE], [FLOW_ID], [APPLICATION_ID], [LOG_LEVEL], [LOG_TIMESTAMP], [EVENT_ID], [FLOW_NAME], [PROCESS], [REQUEST_TIMESTAMP], [SOURCE], [TARGET], [STEP], [DESCRIPTION], [LOG_SEQUENCE], [CREATED_DATETIME], [CUSTOM_FIELD])
VALUES
('7AF12EBE-93AC-443F-82CD-9079C2851C9E', '8C519F41-1F06-41E5-9647-25554315E1C7', 'NULL', 'TRIGGER', 'appIdString', 'DEBUG', '2019-04-26 14:08:25.690', 'C0F40CA0-682C-11E9-AB6D-0298370A6804', 'trigger-melto', 'imp-trigger', '2019-04-26 14:08:23.660', 'SomeSource', 'SomeTarget', 'INBOUND', 'Some description', '3', '2019-04-26 14:08:29.270', 'NULL');
INSERT [dbo].[LOG]
([ID], [CORRELATION_ID], [ERROR_CODE], [FLOW_ID], [APPLICATION_ID], [LOG_LEVEL], [LOG_TIMESTAMP], [EVENT_ID], [FLOW_NAME], [PROCESS], [REQUEST_TIMESTAMP], [SOURCE], [TARGET], [STEP], [DESCRIPTION], [LOG_SEQUENCE], [CREATED_DATETIME], [CUSTOM_FIELD])
VALUES
('E0F5018E-8876-4929-828B-E1DB26CF7F30', '8C519F41-1F06-41E5-9647-25554315E1C7', 'NULL', 'TRIGGER', 'appIdString', 'DEBUG', '2019-04-26 14:08:25.477', 'C0F40CA0-682C-11E9-AB6D-0298370A6804', 'trigger-melto', 'imp-trigger', '2019-04-26 14:08:23.660', 'SomeSource', 'SomeTarget', 'OUTBOUND', 'Some description', '2', '2019-04-26 14:08:29.447', 'NULL');
INSERT [dbo].[LOG]
([ID], [CORRELATION_ID], [ERROR_CODE], [FLOW_ID], [APPLICATION_ID], [LOG_LEVEL], [LOG_TIMESTAMP], [EVENT_ID], [FLOW_NAME], [PROCESS], [REQUEST_TIMESTAMP], [SOURCE], [TARGET], [STEP], [DESCRIPTION], [LOG_SEQUENCE], [CREATED_DATETIME], [CUSTOM_FIELD])
VALUES
('8B7A0A86-14D8-4E72-8047-21A73ECF6157', '8C519F41-1F06-41E5-9647-25554315E1C7', '504', 'TRIGGER', 'appIdString', 'DEBUG', '2019-04-26 14:08:35.833', 'C0F40CA0-682C-11E9-AB6D-0298370A6804', 'trigger-melto', 'imp-trigger', '2019-04-26 14:08:23.660', 'SomeSource', 'SomeTarget', 'ERROR', 'Some description', '5', '2019-04-26 14:08:37.500', 'NULL');
-- Message
INSERT INTO [dbo].[MESSAGE]
([ID] ,[URL] ,[METHOD] ,[MSGBLOB] ,[HEADERS] ,[CREATED_DATETIME])
VALUES
('C56BBFBE-5308-4242-ACD0-383F016C0AD1', 'https://localhost:1234/api/trigger', 'POST', 'U29tZSBtZXNzYWdlIGJsb2IgdG8gZGVjb2Rl', '{"Content-Type":"application/xml"}', '2019-04-26 14:08:25.577');
INSERT INTO [dbo].[MESSAGE]
([ID] ,[URL] ,[METHOD] ,[MSGBLOB] ,[HEADERS] ,[CREATED_DATETIME])
VALUES
('273F4E0A-CA7A-40B5-AF54-F2A53A776541', 'NULL', 'NULL', 'U29tZSBtZXNzYWdlIGJsb2IgdG8gZGVjb2Rl', 'null', '2019-04-26 14:08:29.813');
INSERT INTO [dbo].[MESSAGE]
([ID] ,[URL] ,[METHOD] ,[MSGBLOB] ,[HEADERS] ,[CREATED_DATETIME])
VALUES
('E0F5018E-8876-4929-828B-E1DB26CF7F30', 'NULL', 'NULL', 'U29tZSBtZXNzYWdlIGJsb2IgdG8gZGVjb2Rl', 'null', '2019-04-26 14:08:29.613');
INSERT INTO [dbo].[MESSAGE]
([ID] ,[URL] ,[METHOD] ,[MSGBLOB] ,[HEADERS] ,[CREATED_DATETIME])
VALUES
('8B7A0A86-14D8-4E72-8047-21A73ECF6157', 'NULL', 'NULL', 'U29tZSBtZXNzYWdlIGJsb2IgdG8gZGVjb2Rl', 'null', '2019-04-26 14:08:37.817');
-- Log_Logs
INSERT [dbo].[LOG_LOGS]
([CorrelationId], [LinkedCorrelationId], [CreatedDatetime])
VALUES
('8C519F41-1F06-41E5-9647-25554315E1C7', '972039B5-346B-4BC8-AE9B-2A45D51DA310', '2019-06-19 10:54:33.023');
INSERT [dbo].[LOG_LOGS]
([CorrelationId], [LinkedCorrelationId], [CreatedDatetime])
VALUES
('8C519F41-1F06-41E5-9647-25554315E1C7', '972039B5-346B-4BC8-AE9B-2A45D51DA310', '2019-06-19 10:54:33.023');
INSERT [dbo].[LOG_LOGS]
([CorrelationId], [LinkedCorrelationId], [CreatedDatetime])
VALUES
('8C519F41-1F06-41E5-9647-25554315E1C7', '972039B5-346B-4BC8-AE9B-2A45D51DA310', '2019-06-19 10:54:33.023');
INSERT [dbo].[LOG_LOGS]
([CorrelationId], [LinkedCorrelationId], [CreatedDatetime])
VALUES
('8C519F41-1F06-41E5-9647-25554315E1C7', '972039B5-346B-4BC8-AE9B-2A45D51DA310', '2019-06-19 10:54:33.023');
INSERT [dbo].[LOG_LOGS]
([CorrelationId], [LinkedCorrelationId], [CreatedDatetime])
VALUES
('8C519F41-1F06-41E5-9647-25554315E1C7', '972039B5-346B-4BC8-AE9B-2A45D51DA310', '2019-06-19 10:54:33.023');
What i need as a result (paged by 10,20 or 50 records)
Grouped by the Log.CorrId
Log.ReqTimestamp (should be the same for all Log.CorId)
Log.Source (should be the same for all Log.CorId)
Log.Target (should be the same for all Log.CorId)
Log.FlowName (not the same for all Log.CorId: so where Log.Step =
'OUTBOUND', if not available Log.Step = 'END', if not available any
is ok)
CanResubmit: SUM(case when l.STEP = 'START' and DATALENGTH(m.MSGBLOB) > 0 then 1 else 0 end)
HasError: SUM(case when l.STEP = 'ERROR' then 1 else 0 end)
HasEnd: SUM(case when l.STEP = 'END' then 1 else 0 end)
HasLinkedLog
This is what i have so far.
CREATE PROCEDURE [dbo].[sp_SearchFlowCorrelationIds]
#FlowIdList AS dbo.FlowIdList READONLY,
#CorrelationIdList AS dbo.CorrelationIdList READONLY,
#FlowName nvarchar(50) = null,
#Source nvarchar(256) = null,
#Target nvarchar(256) = null,
#ApplicationId nvarchar(35) = null,
#CustomField nvarchar(60) = null,
#Step nvarchar(50) = null,
#DateFrom datetime = null,
#DateTo datetime = null,
#SortField nvarchar(50) = 'RequestTimestamp',
#SortOrder nvarchar(4) = null,
#Take int = 10,
#Skip int = 0
AS
SET NOCOUNT ON
DECLARE #DateBoundaryFrom int = 1;
DECLARE #DateBoundaryTo int = 13;
SELECT result.CORRELATION_ID as CorrelationId
, result.REQUEST_TIMESTAMP as RequestTimestamp
, result.FLOW_NAME as FlowName
, result.SOURCE as Source
, result.TARGET as Target
, result.CanResubmit
, result.HasError
, result.HasEnd
, result.LinkedCorrelationId as LinkedCorrelationId
FROM
(SELECT lastLogged.CORRELATION_ID
, lastLogged.REQUEST_TIMESTAMP
, lastLogged.SOURCE
, lastLogged.TARGET
, lastLogged.FLOW_NAME
, l2.CanResubmit as CanResubmit
, l2.HasError as HasError
, l2.HasEnd as HasEnd
, ll.LinkedCorrelationId
, ROW_NUMBER() OVER (PARTITION BY lastLogged.CORRELATION_ID ORDER BY lastLogged.LOG_TIMESTAMP DESC) as dest_rank
FROM LOG as lastLogged
INNER JOIN (
select CORRELATION_ID
, SUM(case when l.STEP = 'START' and DATALENGTH(m.MSGBLOB) > 0 then 1 else 0 end) as CanResubmit
, SUM(case when l.STEP = 'ERROR' then 1 else 0 end) as HasError
, SUM(case when l.STEP = 'END' then 1 else 0 end) as HasEnd
from LOG l
left join MESSAGE m on l.ID = m.ID
Where l.CREATED_DATETIME >= ISNULL(DATEADD(DAY, -#DateBoundaryFrom, #DateFrom), l.CREATED_DATETIME)
AND l.CREATED_DATETIME <= ISNULL(DATEADD(DAY, #DateBoundaryTo, #DateTo), l.CREATED_DATETIME)
group by l.CORRELATION_ID
) as l2 on lastLogged.CORRELATION_ID = l2.CORRELATION_ID
LEFT JOIN LOG_LOGS ll on lastLogged.CORRELATION_ID = ll.CorrelationId
WHERE
lastLogged.CREATED_DATETIME >= ISNULL(DATEADD(DAY, -#DateBoundaryFrom, #DateFrom), lastLogged.CREATED_DATETIME)
AND lastLogged.CREATED_DATETIME <= ISNULL(DATEADD(DAY, #DateBoundaryTo, #DateTo), lastLogged.CREATED_DATETIME)
AND lastLogged.REQUEST_TIMESTAMP >= ISNULL(#DateFrom, lastLogged.REQUEST_TIMESTAMP)
AND lastLogged.REQUEST_TIMESTAMP <= ISNULL(#DateTo, lastLogged.REQUEST_TIMESTAMP)
AND (lastLogged.FLOW_ID in (SELECT Flow_Id FROM #FlowIdList) OR NOT EXISTS (select 1 from #FlowIdList))
AND (lastLogged.CORRELATION_ID in (SELECT ID FROM #CorrelationIdList) OR NOT EXISTS (select 1 from #CorrelationIdList))
AND lastLogged.FLOW_NAME = ISNULL(#FlowName, lastLogged.FLOW_NAME)
AND lastLogged.SOURCE = ISNULL(#Source, lastLogged.SOURCE)
AND lastLogged.TARGET = ISNULL(#Target, lastLogged.TARGET)
AND lastLogged.APPLICATION_ID = ISNULL(#ApplicationId, lastLogged.APPLICATION_ID)
AND lastLogged.STEP = ISNULL(#Step, lastLogged.STEP)
AND (lastLogged.CUSTOM_FIELD = #CustomField OR #CustomField IS NULL)
) AS result
WHERE result.dest_rank = 1
ORDER BY
-- ASCENDING
CASE
WHEN #SortOrder <> 'ASC' then cast(null as date)
WHEN #SortField = 'RequestTimestamp' then result.REQUEST_TIMESTAMP
end ASC
, CASE
WHEN #SortOrder <> 'ASC' then cast(null as uniqueidentifier)
WHEN #SortField = 'CorrelationId' then result.CORRELATION_ID
end ASC
, CASE
WHEN #SortOrder <> 'ASC' then ''
WHEN #SortField = 'FlowName' then result.FLOW_NAME
end ASC
, CASE
WHEN #SortOrder <> 'ASC' then ''
WHEN #SortField = 'Source' then result.SOURCE
end ASC
, CASE
WHEN #SortOrder <> 'ASC' then ''
WHEN #SortField = 'Target' then result.TARGET
end ASC
-- DESCENDING
, CASE
WHEN #SortOrder <> 'DESC' then cast(null as date)
WHEN #SortField = 'RequestTimestamp' then result.REQUEST_TIMESTAMP
end DESC
, CASE
WHEN #SortOrder <> 'DESC' then cast(null as uniqueidentifier)
WHEN #SortField = 'CorrelationId' then result.CORRELATION_ID
end DESC
, CASE
WHEN #SortOrder <> 'DESC' then ''
WHEN #SortField = 'FlowName' then result.FLOW_NAME
end DESC
, CASE
WHEN #SortOrder <> 'DESC' then ''
WHEN #SortField = 'Source' then result.SOURCE
end DESC
, CASE
WHEN #SortOrder <> 'DESC' then ''
WHEN #SortField = 'Target' then result.TARGET
end DESC
OFFSET #skip ROWS FETCH NEXT #take ROWS ONLY
Question
Now the question is how do i get that FlowName in there based on the following conditions:
where Log.Step = 'OUTBOUND', if not available Log.Step = 'END', if not available any is ok)
(if there are any performance improvements tips, they are always welcome, because this one takes like 8 or more seconds on 7ml records)

Related

Conditional Grouping

I have item and buyer tables. Both tables have their individual category tables i.e. itemCategory and buyerCategory
CREATE TABLE #itemCategory
(
itemCategoryCode char(4) NOT NULL PRIMARY KEY
, itemCategoryName char(20) NOT NULL
);
INSERT INTO #itemCategory
VALUES ('I001', 'Item Category A')
,('I002', 'Item Category B')
,('I003', 'Item Category C');
CREATE TABLE #buyerCategory
(
buyerCategoryCode char(4) NOT NULL PRIMARY KEY
, buyerCategoryName char(20) NOT NULL
);
INSERT INTO #buyerCategory
VALUES ('B001', 'Buyer Category A')
,('B002', 'Buyer Category B')
,('B003', 'Buyer Category C');
CREATE TABLE #item
(
itemCode char(5) NOT NULL PRIMARY KEY
, itemName char(30) NOT NULL
, itemCategoryCode char(4) NOT NULL FOREIGN KEY REFERENCES itemCategory(itemCategoryCode)
);
INSERT INTO #item
VALUES ('IT001', 'Item A', 'I001')
, ('IT002', 'Item AA', 'I001')
, ('IT003', 'Item AAA', 'I001')
, ('IT004', 'Item B', 'I002')
, ('IT005', 'Item BB', 'I002')
, ('IT006', 'Item BBB', 'I002')
, ('IT007', 'Item C', 'I003')
, ('IT008', 'Item CC', 'I003')
, ('IT009', 'Item CCC', 'I003');
CREATE TABLE #buyer
(
buyerCode char(5) NOT NULL PRIMARY KEY
, buyerName char(30) NOT NULL
, buyerCategoryCode char(4) NOT NULL FOREIGN KEY REFERENCES buyerCategory(buyerCategoryCode)
);
INSERT INTO #buyer
VALUES ('BY001', 'Buyer A', 'B001')
, ('BY002', 'Buyer AA', 'B001')
, ('BY003', 'Buyer AAA', 'B001')
, ('BY004', 'Buyer B', 'B002')
, ('BY005', 'Buyer BB', 'B002')
, ('BY006', 'Buyer BBB', 'B002')
, ('BY007', 'Buyer C', 'B003')
, ('BY008', 'Buyer CC', 'B003')
, ('BY009', 'Buyer CCC', 'B003');
I have a table itemRate table which define rate of item for individual buyer which also has isActive column.
CREATE TABLE #itemRate
(
itemCode char(5) NOT NULL FOREIGN KEY REFERENCES item(itemCode)
, buyerCode char(5) NOT NULL FOREIGN KEY REFERENCES buyer(buyerCode)
, [rate] int NULL
, isActive NOT NULL BIT
);
INSERT INTO #itemRate
VALUES ('IT001', 'BY001', 3.5, '1')
, ('IT002', 'BY001', 4.5, '1')
, ('IT003', 'BY001', 5.5, '0')
, ('IT004', 'BY004', 1.5, '0')
, ('IT005', 'BY004', 2.5, '1')
, ('IT006', 'BY004', 7.5, '0')
, ('IT006', 'BY005', 5.5, '1')
, ('IT005', 'BY005', 2.5, '0')
, ('IT001', 'BY007', 2.5, '0')
, ('IT002', 'BY008', 4.5, '0')
, ('IT003', 'BY007', 6.5, '0');
I am looking for a SQL query where I can get result of following columns itemCategoryCode, buyerCategoryCode, [rate]
There can be multiple scenarios on itemRate table and in all cases query will collect MAX([rate]) column while grouping for itemCategoryCode and buyerCategoryCode
Only exception is when there is multiple items (under same itemCategory) has rates value to the same buyer (not same buyerCategory) and there are no other buyer of the same buyerCategory then system will get the MAX[rate] value of only isActive=1 records.
In the sample data of itemRate table, the result of the query should be
itemCategoryCode
buyerCategoryCode
rate
I001
B001
4.5
I002
B002
7.5
I001
B003
6.5
Let me explain further. a) It is not mandatory that all buyers under the same buyerCategory has any rates defined in itemRates table.
b) In the sample data, where IT003 is bought by BY001 for rate of 5.5 but because there are no other buyer (of same buyerCategory) who have bought any items of itemCategory I001, and since isActive of that record (IT003, BY001, 5.5, 0) is false, the query will not consider it in MAX.
Now compare this with sample data ('IT001', 'BY007', 2.5, '0'), ('IT002', 'BY008', 4.5, '0') and ('IT003', 'BY007', 6.5, '0'); although all this record have false value in isActive but since there are two buyers of same buyerCategory i.e. BY007 and BY008... the query will not consider isActive value hence result of MAX([rate]) would be 6.5.
I hope I clarified my requirements clearly... please let me know, if you need any further clarifications.
Thanks in advance
Thanks for the additional detail on the requirements. I believe this gets you what you want:
CREATE TABLE #itemCategory
(
itemCategoryCode char(4) NOT NULL PRIMARY KEY
, itemCategoryName char(20) NOT NULL
);
INSERT INTO #itemCategory
VALUES ('I001', 'Item Category A')
,('I002', 'Item Category B')
,('I003', 'Item Category C');
CREATE TABLE #buyerCategory
(
buyerCategoryCode char(4) NOT NULL PRIMARY KEY
, buyerCategoryName char(20) NOT NULL
);
INSERT INTO #buyerCategory
VALUES ('B001', 'Buyer Category A')
,('B002', 'Buyer Category B')
,('B003', 'Buyer Category C');
CREATE TABLE #item
(
itemCode char(5) NOT NULL PRIMARY KEY
, itemName char(30) NOT NULL
, itemCategoryCode char(4) NOT NULL FOREIGN KEY REFERENCES itemCategory(itemCategoryCode)
);
INSERT INTO #item
VALUES ('IT001', 'Item A', 'I001')
, ('IT002', 'Item AA', 'I001')
, ('IT003', 'Item AAA', 'I001')
, ('IT004', 'Item B', 'I002')
, ('IT005', 'Item BB', 'I002')
, ('IT006', 'Item BBB', 'I002')
, ('IT007', 'Item C', 'I003')
, ('IT008', 'Item CC', 'I003')
, ('IT009', 'Item CCC', 'I003');
CREATE TABLE #buyer
(
buyerCode char(5) NOT NULL PRIMARY KEY
, buyerName char(30) NOT NULL
, buyerCategoryCode char(4) NOT NULL FOREIGN KEY REFERENCES buyerCategory(buyerCategoryCode)
);
INSERT INTO #buyer
VALUES ('BY001', 'Buyer A', 'B001')
, ('BY002', 'Buyer AA', 'B001')
, ('BY003', 'Buyer AAA', 'B001')
, ('BY004', 'Buyer B', 'B002')
, ('BY005', 'Buyer BB', 'B002')
, ('BY006', 'Buyer BBB', 'B002')
, ('BY007', 'Buyer C', 'B003')
, ('BY008', 'Buyer CC', 'B003')
, ('BY009', 'Buyer CCC', 'B003');
CREATE TABLE #itemRate
(
itemCode char(5) NOT NULL FOREIGN KEY REFERENCES item(itemCode)
, buyerCode char(5) NOT NULL FOREIGN KEY REFERENCES buyer(buyerCode)
, [rate] decimal(2,1) NULL
, isActive bit not NULL
);
INSERT INTO #itemRate
VALUES ('IT001', 'BY001', 3.5, '1')
, ('IT002', 'BY001', 4.5, '1')
, ('IT003', 'BY001', 5.5, '0')
, ('IT004', 'BY004', 1.5, '0')
, ('IT005', 'BY004', 2.5, '1')
, ('IT006', 'BY004', 7.5, '0')
, ('IT006', 'BY005', 5.5, '1')
, ('IT005', 'BY005', 2.5, '0')
, ('IT001', 'BY007', 2.5, '0')
, ('IT002', 'BY008', 4.5, '0')
, ('IT003', 'BY007', 6.5, '0');
with #ratesAndCategories as
(
select ir.*, bu.buyerCategoryCode, it.itemCategoryCode
from #itemRate ir
join #buyer bu on bu.buyerCode = ir.buyerCode
join #item it on it.itemCode = ir.itemCode
)
select rc.itemCategoryCode,
rc.buyerCategoryCode,
--max(iif(otherBuyers.c = 0 and rc.isActive = 0, null, rc.rate))
max(case when otherBuyers.c = 0 and rc.isActive = 0 then null else rc.rate end)
from #ratesAndCategories rc
cross apply (
select count(*)
from #ratesAndCategories
where buyerCode != rc.buyerCode
and buyerCategoryCode = rc.buyerCategoryCode
and itemCategoryCode = rc.itemCategoryCode
) otherBuyers(c)
group by rc.itemCategoryCode,
rc.buyerCategoryCode;

Join tables with rows to columns conversion

I have two tables:
Output need to be like this:
select CODE, NAME,
substring_index(DVAR, ',', 1) as DATA1,
(case when numc >= 2 then substring_index(substring_index(DVAR, ',', 2), ',', -1) end) as DATA2,
(case when numc >= 3 then substring_index(substring_index(DVAR, ',', 3), ',', -1) end) as DATA3,
(case when numc >= 4 then substring_index(substring_index(DVAR, ',', 4), ',', -1) end) as DATA4,
(case when numc >= 5 then substring_index(substring_index(DVAR, ',', 5), ',', -1) end) as DATA5,
(case when numc >= 6 then substring_index(substring_index(DVAR, ',', 6), ',', -1) end) as DATA6,
(case when numc >= 7 then substring_index(substring_index(DVAR, ',', 7), ',', -1) end) as DATA7,
(case when numc >= 8 then substring_index(substring_index(DVAR, ',', 8), ',', -1) end) as DATA8,
(case when numc >= 9 then substring_index(substring_index(DVAR, ',', 9), ',', -1) end) as DATA9,
(case when numc >= 10 then substring_index(substring_index(DVAR, ',', 10), ',', -1) end) as DATA10
FROM (
SELECT T2.CODE, T1.NAME, GROUP_CONCAT(T2.DATA SEPARATOR ',') AS DVAR, count(*) as numc
FROM TABLE2 AS T2
LEFT JOIN TABLE1 AS T1 ON T1.CODE=T2.CODE
GROUP BY T2.CODE
) t
I used this code in MySQL and its working.
But I don't know how to do in SQL Server 2012.
You can use PIVOT for a similar effect, eg
CREATE TABLE tbl1 (
Code CHAR(5) NOT NULL,
[Name] VARCHAR(20) NOT NULL
)
CREATE TABLE tbl2 (
Code CHAR(5) NOT NULL,
[Data] VARCHAR(20) NOT NULL
)
INSERT INTO tbl1 ( Code, [Name] )
VALUES
( 'ST101', 'Item1' ),
( 'ST102', 'Item2' ),
( 'ST103', 'Item3' ),
( 'ST104', 'Item4' ),
( 'ST105', 'Item5' )
INSERT INTO tbl2 ( Code, [Data] )
VALUES
( 'ST101', '12345' ),
( 'ST101', '123456' ),
( 'ST101', '123123' ),
( 'ST101', '12412' ),
( 'ST105', '123123' ),
( 'ST105', '11' ),
( 'ST105', '51231' ),
( 'ST105', '411123' ),
( 'ST103', '112312' ),
( 'ST103', '51231' ),
( 'ST103', '442424' ),
( 'ST103', '4233' ),
( 'ST103', '23123' ),
( 'ST103', '1231' ),
( 'ST104', '12312' ),
( 'ST102', '1231' ),
( 'ST102', '51231' ),
( 'ST102', '66452' ),
( 'ST102', '51115' )
GO
;WITH cte AS (
SELECT
t1.Code,
t1.[Name],
t2.[Data],
'Data' + CAST( ROW_NUMBER() OVER( PARTITION BY t1.Code ORDER BY ( SELECT NULL ) ) AS VARCHAR(20) ) rn
FROM tbl1 t1
INNER JOIN tbl2 t2 ON t1.Code = t2.Code
)
SELECT *
FROM cte
PIVOT ( MAX( Data ) For rn In ( Data1, Data2, Data3, Data4, Data5, Data6, Data7, Data8, Data9, Data10 ) ) pvt
If the number of data items is greater than 10 or unknown you should look at dynamic pivot.

Unexpected behavior using transform column and transform table, SymmetricDS

I have the followings transformation columns
insert into SYM_TRANSFORM_COLUMN (
transform_id, include_on, target_column_name, source_column_name, pk,
transform_type, transform_expression, transform_order, last_update_time,
create_time
) values (
'send_source_node_id', '*', 'node_id', 'employee_id', 1,
'bsh', 'String node = targetNode.getNodeId(); String value = currentValue; return value + "-" + sourceNodeId;', 1, current_timestamp, current_timestamp
);
insert into SYM_TRANSFORM_COLUMN (
transform_id, include_on, target_column_name, source_column_name, pk,
transform_type, transform_expression, transform_order, last_update_time,
create_time
) values (
'copy_employee_id', '*', 'employee_id', 'employee_id', 0,
'copy', '', 10, current_timestamp, current_timestamp
);
insert into SYM_TRANSFORM_COLUMN (
transform_id, include_on, target_column_name, source_column_name, pk,
transform_type, transform_expression, transform_order, last_update_time,
create_time
) values (
'copy_employee_name', '*', 'name', 'name', 0,
'copy', '', 10, current_timestamp, current_timestamp
);
With its transform tables
insert into SYM_TRANSFORM_TABLE (
transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
last_update_time, create_time
) values (
'copy_employee_id', 'school', 'main-school', 'EXTRACT', 'employees',
'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
current_timestamp, current_timestamp
);
insert into SYM_TRANSFORM_TABLE (
transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
last_update_time, create_time
) values (
'copy_employee_name', 'school', 'main-school', 'EXTRACT', 'employees',
'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
current_timestamp, current_timestamp
);
insert into SYM_TRANSFORM_TABLE (
transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
last_update_time, create_time
) values (
'send_source_node_id', 'school', 'main-school', 'EXTRACT', 'employees',
'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
current_timestamp, current_timestamp
);
Structure of my source table
create table employees (
employee_id serial,
name varchar(50),
CONSTRAINT departments_pk PRIMARY KEY (employee_id)
);
Structure of my target table
create table employees (
master_employee_id uuid default uuid_generate_v1(),
employee_id integer,
name varchar(50),
node_id varchar(50),
CONSTRAINT employees_pk PRIMARY KEY (master_employee_id)
);
The synchronization works fine with other tables that are identical, but these tables do not work fine, because when a new employee is added in the source table two records will be added to the target table.
I not idea about this behavior, can someone explain to me?
Example of the result in the target table
Each entry in sym_transform_table represents a table mapping that will process row changes for the source table. Since you have 3 table mappings for the same source table, each row change on that table will result in 3 transformed rows.
I think you wanted to use 1 table mapping in sym_transform_table, like this:
insert into SYM_TRANSFORM_TABLE (
transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
last_update_time, create_time
) values (
'employees_to_employees', 'school', 'main-school', 'EXTRACT', 'employees',
'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
current_timestamp, current_timestamp
);
Then change your entries in sym_transform_column to reference it by using the same "employees_to_employees" transform ID.

Table 'wp_users' already exists

Was working on a site offline and suddenly mysql port clash error came then I had to work on it solution for many hours but no luck. So I took the theme files and database manually from xampp and pasted them into a different computer system with a fresh xampp installed on it. This error is coming now which I have shared above.
WordPress database error: [Table 'wp_users' already exists]
CREATE TABLE wp_users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(255) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(255) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename), KEY user_email (user_email) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_usermeta' already exists]
CREATE TABLE wp_usermeta ( umeta_id bigint(20) unsigned NOT NULL auto_increment, user_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (umeta_id), KEY user_id (user_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_termmeta' already exists]
CREATE TABLE wp_termmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY term_id (term_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_terms' already exists]
CREATE TABLE wp_terms ( term_id bigint(20) unsigned NOT NULL auto_increment, name varchar(200) NOT NULL default '', slug varchar(200) NOT NULL default '', term_group bigint(10) NOT NULL default 0, PRIMARY KEY (term_id), KEY slug (slug(191)), KEY name (name(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_term_taxonomy' already exists]
CREATE TABLE wp_term_taxonomy ( term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default 0, taxonomy varchar(32) NOT NULL default '', description longtext NOT NULL, parent bigint(20) unsigned NOT NULL default 0, count bigint(20) NOT NULL default 0, PRIMARY KEY (term_taxonomy_id), UNIQUE KEY term_id_taxonomy (term_id,taxonomy), KEY taxonomy (taxonomy) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_term_relationships' already exists]
CREATE TABLE wp_term_relationships ( object_id bigint(20) unsigned NOT NULL default 0, term_taxonomy_id bigint(20) unsigned NOT NULL default 0, term_order int(11) NOT NULL default 0, PRIMARY KEY (object_id,term_taxonomy_id), KEY term_taxonomy_id (term_taxonomy_id) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_commentmeta' already exists]
CREATE TABLE wp_commentmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, comment_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY comment_id (comment_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_comments' already exists]
CREATE TABLE wp_comments ( comment_ID bigint(20) unsigned NOT NULL auto_increment, comment_post_ID bigint(20) unsigned NOT NULL default '0', comment_author tinytext NOT NULL, comment_author_email varchar(100) NOT NULL default '', comment_author_url varchar(200) NOT NULL default '', comment_author_IP varchar(100) NOT NULL default '', comment_date datetime NOT NULL default '0000-00-00 00:00:00', comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', comment_content text NOT NULL, comment_karma int(11) NOT NULL default '0', comment_approved varchar(20) NOT NULL default '1', comment_agent varchar(255) NOT NULL default '', comment_type varchar(20) NOT NULL default '', comment_parent bigint(20) unsigned NOT NULL default '0', user_id bigint(20) unsigned NOT NULL default '0', PRIMARY KEY (comment_ID), KEY comment_post_ID (comment_post_ID), KEY comment_approved_date_gmt (comment_approved,comment_date_gmt), KEY comment_date_gmt (comment_date_gmt), KEY comment_parent (comment_parent), KEY comment_author_email (comment_author_email(10)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_links' already exists]
CREATE TABLE wp_links ( link_id bigint(20) unsigned NOT NULL auto_increment, link_url varchar(255) NOT NULL default '', link_name varchar(255) NOT NULL default '', link_image varchar(255) NOT NULL default '', link_target varchar(25) NOT NULL default '', link_description varchar(255) NOT NULL default '', link_visible varchar(20) NOT NULL default 'Y', link_owner bigint(20) unsigned NOT NULL default '1', link_rating int(11) NOT NULL default '0', link_updated datetime NOT NULL default '0000-00-00 00:00:00', link_rel varchar(255) NOT NULL default '', link_notes mediumtext NOT NULL, link_rss varchar(255) NOT NULL default '', PRIMARY KEY (link_id), KEY link_visible (link_visible) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_options' already exists]
CREATE TABLE wp_options ( option_id bigint(20) unsigned NOT NULL auto_increment, option_name varchar(191) NOT NULL default '', option_value longtext NOT NULL, autoload varchar(20) NOT NULL default 'yes', PRIMARY KEY (option_id), UNIQUE KEY option_name (option_name) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_postmeta' already exists]
CREATE TABLE wp_postmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, post_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY post_id (post_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'wp_posts' already exists]
CREATE TABLE wp_posts ( ID bigint(20) unsigned NOT NULL auto_increment, post_author bigint(20) unsigned NOT NULL default '0', post_date datetime NOT NULL default '0000-00-00 00:00:00', post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content longtext NOT NULL, post_title text NOT NULL, post_excerpt text NOT NULL, post_status varchar(20) NOT NULL default 'publish', comment_status varchar(20) NOT NULL default 'open', ping_status varchar(20) NOT NULL default 'open', post_password varchar(255) NOT NULL default '', post_name varchar(200) NOT NULL default '', to_ping text NOT NULL, pinged text NOT NULL, post_modified datetime NOT NULL default '0000-00-00 00:00:00', post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content_filtered longtext NOT NULL, post_parent bigint(20) unsigned NOT NULL default '0', guid varchar(255) NOT NULL default '', menu_order int(11) NOT NULL default '0', post_type varchar(20) NOT NULL default 'post', post_mime_type varchar(100) NOT NULL default '', comment_count bigint(20) NOT NULL default '0', PRIMARY KEY (ID), KEY post_name (post_name(191)), KEY type_status_date (post_type,post_status,post_date,ID), KEY post_parent (post_parent), KEY post_author (post_author) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT option_name FROM wp_options WHERE option_name in ( 'siteurl', 'home', 'blogname', 'blogdescription', 'users_can_register', 'admin_email', 'start_of_week', 'use_balanceTags', 'use_smilies', 'require_name_email', 'comments_notify', 'posts_per_rss', 'rss_use_excerpt', 'mailserver_url', 'mailserver_login', 'mailserver_pass', 'mailserver_port', 'default_category', 'default_comment_status', 'default_ping_status', 'default_pingback_flag', 'posts_per_page', 'date_format', 'time_format', 'links_updated_date_format', 'comment_moderation', 'moderation_notify', 'permalink_structure', 'rewrite_rules', 'hack_file', 'blog_charset', 'moderation_keys', 'active_plugins', 'category_base', 'ping_sites', 'comment_max_links', 'gmt_offset', 'default_email_category', 'recently_edited', 'template', 'stylesheet', 'comment_whitelist', 'blacklist_keys', 'comment_registration', 'html_type', 'use_trackback', 'default_role', 'db_version', 'uploads_use_yearmonth_folders', 'upload_path', 'blog_public', 'default_link_category', 'show_on_front', 'tag_base', 'show_avatars', 'avatar_rating', 'upload_url_path', 'thumbnail_size_w', 'thumbnail_size_h', 'thumbnail_crop', 'medium_size_w', 'medium_size_h', 'avatar_default', 'large_size_w', 'large_size_h', 'image_default_link_type', 'image_default_size', 'image_default_align', 'close_comments_for_old_posts', 'close_comments_days_old', 'thread_comments', 'thread_comments_depth', 'page_comments', 'comments_per_page', 'default_comments_page', 'comment_order', 'sticky_posts', 'widget_categories', 'widget_text', 'widget_rss', 'uninstall_plugins', 'timezone_string', 'page_for_posts', 'page_on_front', 'default_post_format', 'link_manager_enabled', 'finished_splitting_shared_terms', 'site_icon', 'medium_large_size_w', 'medium_large_size_h', 'wp_page_for_privacy_policy', 'show_comments_cookies_opt_in', 'initial_db_version' )
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
INSERT INTO wp_options (option_name, option_value, autoload) VALUES ('siteurl', 'http://localhost/wordpress', 'yes'), ('home', 'http://localhost/wordpress', 'yes'), ('blogname', 'My Site', 'yes'), ('blogdescription', 'Just another WordPress site', 'yes'), ('users_can_register', '0', 'yes'), ('admin_email', 'you#example.com', 'yes'), ('start_of_week', '1', 'yes'), ('use_balanceTags', '0', 'yes'), ('use_smilies', '1', 'yes'), ('require_name_email', '1', 'yes'), ('comments_notify', '1', 'yes'), ('posts_per_rss', '10', 'yes'), ('rss_use_excerpt', '0', 'yes'), ('mailserver_url', 'mail.example.com', 'yes'), ('mailserver_login', 'login#example.com', 'yes'), ('mailserver_pass', 'password', 'yes'), ('mailserver_port', '110', 'yes'), ('default_category', '1', 'yes'), ('default_comment_status', 'open', 'yes'), ('default_ping_status', 'open', 'yes'), ('default_pingback_flag', '1', 'yes'), ('posts_per_page', '10', 'yes'), ('date_format', 'F j, Y', 'yes'), ('time_format', 'g:i a', 'yes'), ('links_updated_date_format', 'F j, Y g:i a', 'yes'), ('comment_moderation', '0', 'yes'), ('moderation_notify', '1', 'yes'), ('permalink_structure', '', 'yes'), ('rewrite_rules', '', 'yes'), ('hack_file', '0', 'yes'), ('blog_charset', 'UTF-8', 'yes'), ('moderation_keys', '', 'no'), ('active_plugins', 'a:0:{}', 'yes'), ('category_base', '', 'yes'), ('ping_sites', 'http://rpc.pingomatic.com/', 'yes'), ('comment_max_links', '2', 'yes'), ('gmt_offset', '0', 'yes'), ('default_email_category', '1', 'yes'), ('recently_edited', '', 'no'), ('template', 'twentynineteen', 'yes'), ('stylesheet', 'twentynineteen', 'yes'), ('comment_whitelist', '1', 'yes'), ('blacklist_keys', '', 'no'), ('comment_registration', '0', 'yes'), ('html_type', 'text/html', 'yes'), ('use_trackback', '0', 'yes'), ('default_role', 'subscriber', 'yes'), ('db_version', '44719', 'yes'), ('uploads_use_yearmonth_folders', '1', 'yes'), ('upload_path', '', 'yes'), ('blog_public', '1', 'yes'), ('default_link_category', '2', 'yes'), ('show_on_front', 'posts', 'yes'), ('tag_base', '', 'yes'), ('show_avatars', '1', 'yes'), ('avatar_rating', 'G', 'yes'), ('upload_url_path', '', 'yes'), ('thumbnail_size_w', '150', 'yes'), ('thumbnail_size_h', '150', 'yes'), ('thumbnail_crop', '1', 'yes'), ('medium_size_w', '300', 'yes'), ('medium_size_h', '300', 'yes'), ('avatar_default', 'mystery', 'yes'), ('large_size_w', '1024', 'yes'), ('large_size_h', '1024', 'yes'), ('image_default_link_type', 'none', 'yes'), ('image_default_size', '', 'yes'), ('image_default_align', '', 'yes'), ('close_comments_for_old_posts', '0', 'yes'), ('close_comments_days_old', '14', 'yes'), ('thread_comments', '1', 'yes'), ('thread_comments_depth', '5', 'yes'), ('page_comments', '0', 'yes'), ('comments_per_page', '50', 'yes'), ('default_comments_page', 'newest', 'yes'), ('comment_order', 'asc', 'yes'), ('sticky_posts', 'a:0:{}', 'yes'), ('widget_categories', 'a:0:{}', 'yes'), ('widget_text', 'a:0:{}', 'yes'), ('widget_rss', 'a:0:{}', 'yes'), ('uninstall_plugins', 'a:0:{}', 'no'), ('timezone_string', '', 'yes'), ('page_for_posts', '0', 'yes'), ('page_on_front', '0', 'yes'), ('default_post_format', '0', 'yes'), ('link_manager_enabled', '0', 'yes'), ('finished_splitting_shared_terms', '1', 'yes'), ('site_icon', '0', 'yes'), ('medium_large_size_w', '768', 'yes'), ('medium_large_size_h', '0', 'yes'), ('wp_page_for_privacy_policy', '0', 'yes'), ('show_comments_cookies_opt_in', '1', 'yes'), ('initial_db_version', '44719', 'yes')
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT option_value FROM wp_options WHERE option_name = 'home'
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT option_value FROM wp_options WHERE option_name = 'siteurl'
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SHOW FULL COLUMNS FROM `wp_options`
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('home', 'O:8:\"WP_Error\":2:{s:6:\"errors\";a:1:{s:30:\"wpdb_get_table_charset_failure\";a:1:{i:0;s:0:\"\";}}s:10:\"error_data\";a:0:{}}', 'yes') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT autoload FROM wp_options WHERE option_name = 'blodotgsping_url'
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT autoload FROM wp_options WHERE option_name = 'bodyterminator'
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT autoload FROM wp_options WHERE option_name = 'emailtestonly'
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT autoload FROM wp_options WHERE option_name = 'phoneemail_separator'
WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine]
SELECT autoload FROM wp_options WHERE option_name = 'smilies_directory'
... more code
That means your tables already exist.
Try dropping them before running your SQL queries.
Or
use CREATE TABLE IF NOT EXISTS instead of just CREATE TABLE in your queries.
when you download wordpress it suggests to use wp_ as a prefix for your tables. but you cant have 2 tables with the same name online.
what you have to do is during the wp installation is to change the prefix to something other than wp_.
i had this problem myself when i made some projects in wp and had to upload them online and since the tables have the same names you cant have them in the same database/folder. simply just make sure to always give your project a unique prefix to avoid problems like this.

CakePHP 3 matching and contain not returning association

I'm using CakePHP 3.3.9 and trying to use the friendsofcake/search plugin + pagination to filter a list of AssessmentLogs based on Clients.EmrSystems, in which EmrSystems is a belongsToMany association on Clients. This is all on a SQL Server database if it makes a difference.
My problem is that when I use matching() and contain() I receive the correct results but the Client association is missing from the AssessmentLog record, even though it is explicitly contained. I'm not concerned about getting the EmrSystems for a Client under each AssessmentLog, only the Client that owns it.
The query generated even appears correct, but the ORM just has a null value for the client association on each record. Even _matchingData contains client according to DebugKit, so I know the right info is there. Manually running the generated query even returns the right results.
Here's how the associations are laid out:
AssessmentLogsTable
// AssessmentLog belongs to a Client using ClientId field
$this->belongsTo('Clients', [
'foreignKey' => 'ClientId'
]);
// Search plugin
$this->searchManager()->add('EmrSystem', 'Search.Callback', [
'callback' => function ($query, $args, $manager) {
if (!is_array($args['EmrSystem'])) {
return false;
}
// Not returning the Client association for some reason :(
// Should return only assessment logs where the client has a specified EMR system.
// The AssessmentLog should always contain the Client association
return $query->contain([
'Clients',
'Clients.EmrSystems'
])
->matching('Clients.EmrSystems', function ($q) use ($args) {
return $q->where(function ($exp) use ($args) {
return $exp->in('EmrSystems.ID', $args['EmrSystem']);
});
});
},
'filterEmpty' => true
]);
ClientsTable
// Client has many assessment logs - The ID fields aren't named consistently and wasn't my choice or design. The field name is correct.
$this->hasMany('AssessmentLogs', [
'foreignKey' => 'ClientID'
]);
// Client can have multiple EMR (Electronic Medical Record) systems
$this->belongsToMany('EmrSystems', [
'joinTable' => 'ClientEmrSystem',
'foreignKey' => 'ClientId',
'targetForeignKey' => 'EmrSystemId',
'through' => 'ClientEmrSystems',
'saveStrategy' => 'replace'
]);
AssessmentLogsController
// Load other associations
$this->paginate['contain'] = [
'AssessmentTypes' => function ($q) {
return $q->select([
'AssessmentTypes.AssessmentTypeCd',
'AssessmentTypes.AssessmentTypeShort'
]);
},
'Clients' => function ($q) {
return $q->select([
'Clients.ClientId',
'Clients.OrganizationName'
]);
},
'Patients' => function ($q) {
return $q->select([
'Patients.PatientId',
'Patients.FirstName',
'Patients.LastName'
]);
}
];
// Use Search Plugin
$assessmentLogs = $this->AssessmentLogs->find(
'search',
$this->AssessmentLogs->filterParams($this->request->query)
);
$this->set('assessmentLogs', $this->paginate($assessmentLogs));
Generated Query
I've included some other associations that are working correctly and returning patient names, types, etc.
SELECT
AssessmentLogs.AssessmentLogId AS [AssessmentLogs__AssessmentLogId],
AssessmentLogs.ClientID AS [AssessmentLogs__ClientID],
AssessmentLogs.PatientID AS [AssessmentLogs__PatientID],
AssessmentLogs.AssessmentTypeCd AS [AssessmentLogs__AssessmentTypeCd],
Clients.ClientId AS [Clients__ClientId],
Clients.OrganizationName AS [Clients__OrganizationName],
ClientEmrSystems.ClientId AS [ClientEmrSystems__ClientId],
ClientEmrSystems.EmrSystemId AS [ClientEmrSystems__EmrSystemId],
ClientEmrSystems.Created AS [ClientEmrSystems__Created],
ClientEmrSystems.Modified AS [ClientEmrSystems__Modified],
EmrSystems.ID AS [EmrSystems__ID],
EmrSystems.Name AS [EmrSystems__Name],
EmrSystems.Created AS [EmrSystems__Created],
EmrSystems.Modified AS [EmrSystems__Modified],
AssessmentTypes.AssessmentTypeCd AS [AssessmentTypes__AssessmentTypeCd],
AssessmentTypes.AssessmentTypeShort AS [AssessmentTypes__AssessmentTypeShort],
Patients.PatientId AS [Patients__PatientId],
Patients.FirstName AS [Patients__FirstName],
Patients.LastName AS [Patients__LastName]
FROM
AssessmentLog AssessmentLogs
INNER JOIN Client Clients ON Clients.ClientId = (AssessmentLogs.ClientId)
INNER JOIN ClientEmrSystem ClientEmrSystems ON Clients.ClientId = (ClientEmrSystems.ClientId)
INNER JOIN EmrSystem EmrSystems ON EmrSystems.ID = (ClientEmrSystems.EmrSystemId)
LEFT JOIN AssessmentType AssessmentTypes ON AssessmentTypes.AssessmentTypeCd = (
AssessmentLogs.AssessmentTypeCd
)
LEFT JOIN Patient Patients ON Patients.PatientId = (AssessmentLogs.PatientId)
WHERE
(
EmrSystems.ID in (1)
AND (
AssessmentLogs.Void = 0
)
)
ORDER BY
AssessmentLogs.AssessmentLogId OFFSET 0 ROWS FETCH FIRST 40 ROWS ONLY
Schema Sample
CREATE TABLE [dbo].[Client](
[ClientId] [int] NOT NULL,
[OrganizationName] [varchar](max) NULL,
[Email] [varchar](max) NULL,
[WorkPhone] [varchar](max) NULL,
[Fax] [varchar](max) NULL,
[UpdatedDate] [datetime] NULL,
[Notes] [text] NULL,
CONSTRAINT [PK_Clients] PRIMARY KEY CLUSTERED
(
[ClientId] ASC
)
);
CREATE TABLE [dbo].[AssessmentLog](
[AssessmentLogId] [int] IDENTITY(1,1) NOT NULL,
[ClientID] [int] NOT NULL,
[PatientID] [int] NOT NULL,
[AssessmentTypeCd] [int] NOT NULL,
[Note] [varchar](max) NULL,
[Void] [bit] NOT NULL,
[DateInserted] [datetime] NOT NULL,
[DateCharged] [datetime] NULL,
CONSTRAINT [PK_AssessmentLog] PRIMARY KEY CLUSTERED
(
[AssessmentLogId] ASC
)
);
CREATE TABLE [dbo].[Patient](
[PatientId] [int] IDENTITY(1,1) NOT NULL,
[ClientId] [int] NOT NULL,
[FirstName] [varchar](max) NOT NULL,
[LastName] [varchar](max) NOT NULL,
[MedicalRecordNbr] [varchar](max) NOT NULL,
CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
[PatientId] ASC
)
);
CREATE TABLE [dbo].[AssessmentType](
[AssessmentTypeCd] [int] IDENTITY(1,1) NOT NULL,
[AssessmentTypeShort] [varchar](50) NULL,
[AssessmentTypeLong] [varchar](max) NULL,
CONSTRAINT [PK_AssessmentType] PRIMARY KEY CLUSTERED
(
[AssessmentTypeCd] ASC
)
);
CREATE TABLE [dbo].[EmrSystem](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Created] [datetime2](7) NULL,
[Modified] [datetime2](7) NULL,
CONSTRAINT [PK_EmrSystem] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
);
CREATE TABLE [dbo].[ClientEmrSystem](
[ClientId] [int] NOT NULL,
[EmrSystemId] [int] NOT NULL,
[Created] [datetime2](7) NULL,
[Modified] [datetime2](7) NULL,
CONSTRAINT [PK_ClientEmrSystem] PRIMARY KEY CLUSTERED
(
[ClientId] ASC,
[EmrSystemId] ASC
)
);
Sample Records
Here's sample records. I've specified primary keys even though they're auto-increment/identity columns just for simplicity:
INSERT INTO [dbo].[Client] (
[ClientId],
[OrganizationName],
[Email],
[WorkPhone],
[Fax],
[UpdatedDate],
[Notes],
) VALUES (
123,
'Sample Client',
'sample#sample.com',
'(555) 555-1234',
'(555) 555-5678',
'2016-12-12 12:00:00',
'Sample notes about sample client.'
);
INSERT INTO [dbo].[Patient] (
[PatientId],
[ClientId],
[FirstName],
[LastName],
[MedicalRecordNbr]
) VALUES (
1,
123,
'Some',
'Dude',
'A12345'
);
INSERT INTO [dbo].[AssessmentType] (
[AssessmentTypeCd],
[AssessmentTypeShort],
[AssessmentTypeLong]
) VALUES (
1,
'Sample',
'Sample Chart'
);
INSERT INTO [dbo].[EmrSystem] (
[ID],
[Name],
[Created],
[Modified]
) VALUES (
1,
'Some System',
GETDATE(),
GETDATE()
);
INSERT INTO [dbo].[ClientEmrSystem] (
[ClientId],
[EmrSystemId],
[Created],
[Modified]
) VALUES (
123,
1,
GETDATE(),
GETDATE()
);
INSERT INTO [dbo].[AssessmentLog] (
[ClientID],
[PatientID],
[AssessmentTypeCd],
[Note],
[Void],
[DateInserted],
[DateCharged]
) VALUES (
123,
1,
1,
'Sample notes',
0,
GETDATE(),
NULL
);
Oddly, when using the EMR System filter, the fields under the Client association are not limited either. It returns everything. I tried adjusting the contain[] array to include the limited fields, but everything is ignored.
I'm assuming I did something wrong and its not Cake's fault, but I can't seem to figure out an elegant solution. Thank you for any help :) It is greatly appreciated.

Resources