Creating a SSRS report and having issues with structure - reporting-services

I am trying to create a report for some calibrated tools from our ERP System.
I am fairly new to SSRS and not sure how to structure it.
We would like to have 6 columns:
PART_ID, Description, Calibration_Required, Calibrated_Date, Next_Calibration, Employee
This Information is located in 4 Columns in the Table and are Defined by Field ID:
Part_ID
Description
Date_Val
String_Val
Field_ID
00004 = Calibrated Date From Date_Val
00005 = Next Calibration From Date_Val
00006 = Employee From String_Val
00007 = Calibration Required From String_Val
I would like to have each row in its own column and to only have the part listed once instead of 4 Times for each Field_ID.

I used a common table expression CTE to pivot the recordset. To mock up the data I used mockaroo.
Results
Example Records
Example SQL
WITH
field_descriptions
AS
(
SELECT tbl.* FROM (VALUES
( '00004', 'Calibrated Date')
, ( '00005', 'Next Calibration')
, ( '00006', 'Employee')
, ( '00007', 'Calibration Required')
) tbl ([Field_ID], [Field_Description])
)
,
part_data
AS
(
SELECT tbl.* FROM (VALUES
( 10001, '00004', 'NSX', '26-Jan-2019', NULL)
, ( 10001, '00005', 'NSX', '23-Aug-2018', NULL)
, ( 10001, '00006', 'NSX', NULL, 'aludlom1')
, ( 10001, '00007', 'NSX', NULL, 'tweek0')
, ( 10002, '00004', 'S2000', '19-Aug-2018', NULL)
, ( 10002, '00005', 'S2000', '31-Aug-2018', NULL)
, ( 10002, '00006', 'S2000', NULL, 'mmiskelly7')
, ( 10002, '00007', 'S2000', NULL, 'btwitty2')
, ( 10003, '00004', 'LHS', '15-Jun-2018', NULL)
, ( 10003, '00005', 'LHS', '16-Sep-2018', NULL)
, ( 10003, '00006', 'LHS', NULL, 'ceronief')
, ( 10003, '00007', 'LHS', NULL, 'rmccaughran5')
, ( 10004, '00004', 'Corvette', '07-Jul-2018', NULL)
, ( 10004, '00005', 'Corvette', '24-Oct-2018', NULL)
, ( 10004, '00006', 'Corvette', NULL, 'jgodonh')
, ( 10004, '00007', 'Corvette', NULL, 'rbrayley8')
, ( 10005, '00004', 'Savana', '14-Oct-2018', NULL)
, ( 10005, '00005', 'Savana', '08-Feb-2018', NULL)
, ( 10005, '00006', 'Savana', NULL, 'dwilsoni')
, ( 10005, '00007', 'Savana', NULL, 'sdunnan9')
, ( 10006, '00004', 'Z4 M', '01-Jan-2019', NULL)
, ( 10006, '00005', 'Z4 M', '07-Dec-2018', NULL)
, ( 10006, '00006', 'Z4 M', NULL, 'ncopestickt')
, ( 10006, '00007', 'Z4 M', NULL, 'tskahilla')
, ( 10007, '00004', 'M-Class', '11-Aug-2018', NULL)
, ( 10007, '00005', 'M-Class', '02-May-2018', NULL)
, ( 10007, '00006', 'M-Class', NULL, 'bbamlingx')
, ( 10007, '00007', 'M-Class', NULL, 'ddunkb')
, ( 10008, '00004', 'Neon', '31-Oct-2018', NULL)
, ( 10008, '00005', 'Neon', '16-Jul-2018', NULL)
, ( 10008, '00006', 'Neon', NULL, 'vtocknell11')
, ( 10008, '00007', 'Neon', NULL, 'thagstonk')
, ( 10009, '00004', 'Celica', '05-Sep-2018', NULL)
, ( 10009, '00005', 'Celica', '16-Mar-2018', NULL)
, ( 10009, '00006', 'Celica', NULL, 'fwudeland1a')
, ( 10009, '00007', 'Celica', NULL, 'wjennionsp')
, ( 10010, '00004', 'Savana', '09-Oct-2018', NULL)
, ( 10010, '00005', 'Savana', '05-Jul-2018', NULL)
, ( 10010, '00006', 'Savana', NULL, 'dtrevena1c')
, ( 10010, '00007', 'Savana', NULL, 'dcaseror')
) tbl ([Part_ID], [Field_ID], [Description], [Date_Val], [String_Val])
)
,
part_data_udf
AS
(
SELECT
pd.[Part_ID]
, pd.[Field_ID]
, fd.[Field_Description]
, pd.[Description]
, pd.[Date_Val]
, pd.[String_Val]
, [udf_field] = COALESCE(REPLACE(CONVERT(VARCHAR(11), pd.[Date_Val], 113), ' ', '-'), pd.[String_Val])
FROM
part_data AS pd
INNER JOIN field_descriptions AS fd ON pd.[Field_ID] = fd.[Field_ID]
)
SELECT
[Part_ID]
, [Description]
, [Calibrated Date]
, [Next Calibration]
, [Employee]
, [Calibration Required]
FROM
(
SELECT
pd.[Part_ID]
, pd.[Field_Description]
, pd.[Description]
, pd.[udf_field]
FROM
part_data_udf pd
) pL
PIVOT
(
MAX([udf_field])
FOR [Field_Description]
IN
(
[Calibrated Date]
, [Next Calibration]
, [Employee]
, [Calibration Required]
)
) AS pvt
ORDER BY [Part_ID]

Related

Next row value without Window functions

I have the following table of page statuses updates. Every row is a status change:
CREATE TABLE `t1` (
`page_id` int(11) NOT NULL,
`country` varchar(2) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`page_id`,`country`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO t1 (page_id, country, status, date)
VALUES (1, 'de', 'deactivated', '2018-09-28 14:52:11' ) ,
(1, 'de', 'activated', '2018-09-28 14:54:18' ) ,
(1, 'de', 'deactivated', '2018-09-28 14:60:12' ) ,
(1, 'de', 'moderated', '2018-09-28 14:54:12' ) ,
(2, 'es', 'deactivated', '2018-09-28 14:52:01' ) ,
(2, 'es', 'activated', '2018-09-28 14:52:07' ) ,
(2, 'es', 'deactivated', '2018-09-28 14:52:11' )
I want to see the table in such a format, so that every row shows since when till when a page had a particular status:
CREATE TABLE `t2` (
`page_id` int(11) NOT NULL,
`country` varchar(2) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`date_from` datetime DEFAULT NULL,
`date_to` datetime DEFAULT NULL,
PRIMARY KEY (`page_id`,`country`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO t2 (page_id, country, status, date_from, date_to)
VALUES (1, 'de', 'deactivated', '2018-09-28 14:52:11', '2018-09-28 14:54:12' ) ,
(1, 'de', 'moderated', '2018-09-28 14:54:12', '2018-09-28 14:54:18' ) ,
(1, 'de', 'activated', '2018-09-28 14:54:18','2018-09-28 14:60:12' ) ,
(1, 'de', 'deactivated', '2018-09-28 14:60:12','2018-01-25 14:60:12' ) ,
(2, 'es', 'deactivated', '2018-09-28 14:52:01','2018-09-28 14:52:07' ) ,
(2, 'es', 'activated', '2018-09-28 14:52:07', '2018-09-28 14:52:11' ) ,
(2, 'es', 'deactivated', '2018-09-28 14:52:11','2018-01-25 14:52:11' ) ;
The problem is that we are still using MySQL 5.7 and haven't upgraded to mysql8 with cte and window functions, which would easily solve the problem:
SELECT
country,
page_id,
status,
date as date_from,
COALESCE(MIN(date) OVER(PARTITION BY country, page_id ORDER BY date DESC
ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING),
TIMESTAMPADD(day, 1, current_timestamp())) as date_to
FROM t1 ;
I assume there should be a trick with self join but can't figure out how exactly!
In MySQL 8+, you would normally use LEAD() for this, rather than your complicated expression.
In earlier versions, you can use a correlated subquery:
select t1.*,
(select tt1.date
from t1 tt1
where tt1.country = t1.country and tt1.page_id = t1.page_id and
tt1.date > t1.date
order by tt1.date asc
limit 1
) as date_to
from t1;
This uses NULL for the date_to values at the end of each sequence. That makes more sense to me.
If you want to repeat the date_from instead (which I don't recommend), then you can do:
select t1.*,
(select min(tt1.date_from, t1.date_from)
from t1 tt1
where tt1.page_id = t1.page_id and
tt1.date_from > t1.date_from
) as date_to
from t1;

Sql query - Cant select the max value of a row

I have this query that showing items in my site.
$sql = "
select p.id
, p.name
, p.logo
, p.short_description
, c.Parent_category
, IF(d.commission_name = 'percent'
, CONCAT(FORMAT(d.action, 2)/2 ,' %')
, CONCAT(FORMAT(d.action,2)/2,' €')) as comms
, GROUP_CONCAT(c.category_name SEPARATOR ',') as category_names
from eshop p
join eshop_cat c
on p.id = c.eshop_id
join eshop_commissions d
on p.id = d.eshop_id
where c.Parent_category = 'fashion'
and p.sites = 1
GROUP
BY d.action DESC
";
The problem is here
IF(d.commission_name = 'percent', CONCAT(FORMAT(d.action, 2)/2 ,' %') ,
CONCAT(FORMAT(d.action,2)/2,' €'))
i need only the biggest value of each eshop id. i tryied with this
IF(d.commission_name = 'percent', CONCAT(FORMAT(max(d.action), 2)/2 ,' %') ,
CONCAT(FORMAT(max(d.action),2)/2,' €'))
but its not working
For example i have 2 entries with the same eshop id
How can i receive only 1 commission that will be the biggest?
eshop_id commission_name action
1 percent 20 (%)
1 fixed_amount 30 (euro)
EDITED
CREATE TABLE `eshop` (
`id` int(11) NOT NULL,
`name` text NOT NULL,
`logo` text NOT NULL,
`short_description` text NOT NULL,
`sites` tinyint(1) NOT NULL,
`url` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`summary` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `eshop_commissions` (
`commission_name` text NOT NULL,
`eshop_id` int(11) NOT NULL,
`action` decimal(10,2) NOT NULL,
`subaction` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `eshop_cat` (
`eshop_id` int(11) NOT NULL,
`category_name` text NOT NULL,
`Parent_category` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `eshop_commissions` (`commission_name`, `eshop_id`, `action`, `subaction`) VALUES
('percent', 100, '12.00', '12.00'),
('fixed_amount', 100, '15.00', '15.00'),
('percent', 100, '5.00', '5.00'),
('percent', 100, '2.00', '2.00');
INSERT INTO `eshop` (`id`, `name`, `logo`, `short_description`, `description`, `sites`, `url, `timestamp`, `summary`) VALUES
(100, 'Tokotoukan', 'logo-tokotoukan.gif', '<p>\r\n !</p>\r\n', '<p>\r\n <font face=\"arial\" size=\"2\">Τo TOKOTOUKAN </font></p>\r\n', 1, 'http://www.com', ''2017-07-07 17:39:59', '15,00%');
INSERT INTO `eshop_cat` (`eshop_id`, `category_name`, `Parent_category`) VALUES
(100, 'fashion', 'fashion');

Is Dynamic SQL The Only Way To Run This?

Each store has its own database (which I agree is bad practice), and I need to get data from all of those individual databases that meet certain criteria. I have come up with this, thus far, but I get an error of
Msg 102, Level 15, State 1, Line 81
Incorrect syntax near ')'.
I think this will show what I need to achieve, is dynamic SQL the best way to perform this task? If so, what do I do to remove my error. If not, what idea/thoughts/re-writes can more advanced SQL users provide.
Create Table #storeinformation
(
storeID int IDENTITY(1,1) PRIMARY KEY
,storename varchar(150)
,storetype varchar(150)
)
Insert INTO #storeinformation Values ('A', 'Corner'), ('B', 'Strip Mall'), ('C', 'Corner'), ('D', 'Corner')
Create Table #storeA
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeA VALUES ('A', 16, '14.23', '18.36', '18.22', NULL, NULL, NULL),('A', 43, '110.23', '181.36', '183.22', NULL, NULL, NULL),('A', 55, '124.23', '182.36', '183.22', 'Yes', 'Yes', 'Yes')
Create Table #storeB
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeB VALUES ('B', 11, '14.23', '18.36', '18.22', 'Yes', NULL, NULL),('B', 13, '110.23', '181.36', '183.22', NULL, NULL, NULL),('B', 52, '124.23', '182.36', '183.22', NULL, 'Yes', NULL)
Create Table #storeC
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeC VALUES ('C', 6, '14.23', '18.36', '18.22', NULL, NULL, 'Yes'),('C', 4, '110.23', '181.36', '183.22', NULL, NULL, NULL),('C', 5, '124.23', '182.36', '183.22', NULL, 'Yes', NULL)
Create Table #storeD
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeD VALUES ('D', '116', '14.23', '18.36', '18.22', 'Yes', 'Yes', 'Yes'),('D', '143', '10.23', '81.36', '18.22', 'Yes', NULL, 'Yes'),('D', '155', '12.23', '1.36', '183.22', 'Yes', NULL, NULL)
Create Table #FullOnFrontalData
(
storename varchar(100)
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,evaluated varchar(10)
)
Insert Into #FullOnFrontalData (storename)
Select storename
FROM #storeinformation
Where storetype = 'Corner'
Declare #storecount int, #dbname varchar(100)
Set #storecount = (Select Count(*) from #FullOnFrontalData)
while #storecount > 0
BEGIN
Set #dbname = (Select Top 1 storename from #FullOnFrontalData where evaluated is null)
EXEC('Update #FullOnFrontalData
Set tobaccosales = (Select SUM(tobaccosales) FROM '+#dbname))
EXEC('Update #FullOnFrontalData
foodsales = (Select SUM(foodsales) FROM '+#dbname))
EXEC('Update #FullOnFrontalData
lotterysales = (Select SUM(lotterysales) FROM '+#dbname))
update #FullOnFrontalData
set evaluated = 1
where storename = #dbname
set #storecount = #storecount - 1
END
Select * from #FullOnFrontalData
Instead of while etc. you can just do it with one update statement.
insert into #FullOnFrontalData
select Sinf.storeid, tab, fod, lott, 1 from (
select storeid, sum(tobaccosales) tab , sum(foodsales) fod, sum(lotterysales) lott
from #storeA
group by storeid
union all
select storeid, sum(tobaccosales) , sum(foodsales), sum(lotterysales)
from #storeB
group by storeid
union all
select storeid, sum(tobaccosales) , sum(foodsales), sum(lotterysales)
from #storeC
group by storeid
union all
select storeid, sum(tobaccosales) , sum(foodsales), sum(lotterysales)
from #storeD
group by storeid ) SInv
join #storeinformation SInf
on Sinv.storeid = Sinf.storename and
Sinf.storetype = 'Corner'
The full version is below:
Create Table #storeinformation
(
storeID int IDENTITY(1,1) PRIMARY KEY
,storename varchar(150)
,storetype varchar(150)
)
Insert INTO #storeinformation Values ('A', 'Corner'), ('B', 'Strip Mall'), ('C', 'Corner'), ('D', 'Corner')
Create Table #storeA
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeA VALUES ('A', 16, '14.23', '18.36', '18.22', NULL, NULL, NULL),('A', 43, '110.23', '181.36', '183.22', NULL, NULL, NULL),('A', 55, '124.23', '182.36', '183.22', 'Yes', 'Yes', 'Yes')
Create Table #storeB
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeB VALUES ('B', 11, '14.23', '18.36', '18.22', 'Yes', NULL, NULL),('B', 13, '110.23', '181.36', '183.22', NULL, NULL, NULL),('B', 52, '124.23', '182.36', '183.22', NULL, 'Yes', NULL)
Create Table #storeC
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeC VALUES ('C', 6, '14.23', '18.36', '18.22', NULL, NULL, 'Yes'),('C', 4, '110.23', '181.36', '183.22', NULL, NULL, NULL),('C', 5, '124.23', '182.36', '183.22', NULL, 'Yes', NULL)
Create Table #storeD
(
storeID varchar(100)
,employeeid int
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,gsmapproval varchar(10)
,BDSMapproval varchar(10)
,RSMapproval varchar(10)
)
Insert INTO #storeD VALUES ('D', '116', '14.23', '18.36', '18.22', 'Yes', 'Yes', 'Yes'),('D', '143', '10.23', '81.36', '18.22', 'Yes', NULL, 'Yes'),('D', '155', '12.23', '1.36', '183.22', 'Yes', NULL, NULL)
Create Table #FullOnFrontalData
(
storename varchar(100)
,tobaccosales decimal(16,4)
,foodsales decimal(16,4)
,lotterysales decimal(16,4)
,evaluated varchar(10)
)
insert into #FullOnFrontalData
select Sinf.storeid, tab, fod, lott, 1 from (
select storeid, sum(tobaccosales) tab , sum(foodsales) fod, sum(lotterysales) lott
from #storeA
group by storeid
union all
select storeid, sum(tobaccosales) , sum(foodsales), sum(lotterysales)
from #storeB
group by storeid
union all
select storeid, sum(tobaccosales) , sum(foodsales), sum(lotterysales)
from #storeC
group by storeid
union all
select storeid, sum(tobaccosales) , sum(foodsales), sum(lotterysales)
from #storeD
group by storeid ) SInv
join #storeinformation SInf
on Sinv.storeid = Sinf.storename and
Sinf.storetype = 'Corner'

modifying this complicated mySql query

I have 2 tables, adds, and adds_filters
Here are my tables:
CREATE TABLE IF NOT EXISTS `adds` (
`addid` int(11) NOT NULL AUTO_INCREMENT,
`memberid` int(11) NOT NULL,
`isnew` int(11) NOT NULL,
`catid` int(11) NOT NULL,
`manufacturerid` int(11) NOT NULL,
`modelid` varchar(255) DEFAULT NULL,
`colorid` int(11) DEFAULT NULL,
`geographicareaid` int(45) NOT NULL,
`addtypeid` varchar(45) NOT NULL,
`addcreatedon` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`addvalidfrom` date NOT NULL,
`addvaliduntil` date NOT NULL,
`addcreatedfromip` varchar(255) NOT NULL,
`yearofmanufacturing` varchar(255) DEFAULT NULL,
`monthofmanufacturing` int(11) DEFAULT NULL,
`hoursused` int(11) DEFAULT NULL,
`cc2` int(11) DEFAULT NULL,
`horsepowers` int(11) DEFAULT NULL,
`metalic` tinyint(4) DEFAULT NULL,
`isdamaged` tinyint(4) DEFAULT NULL,
`price` float DEFAULT NULL,
`hasvat` tinyint(4) NOT NULL,
`canbenegotiated` tinyint(4) DEFAULT NULL,
`addtitle` varchar(255) DEFAULT NULL,
`addtext` text NOT NULL,
`youtubevideo` varchar(255) DEFAULT NULL,
`visible` tinyint(4) DEFAULT NULL,
`ff1` varchar(255) DEFAULT NULL,
`ff2` varchar(255) DEFAULT NULL,
`ff3` varchar(255) DEFAULT NULL,
`ff4` varchar(255) DEFAULT NULL,
PRIMARY KEY (`addid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=43 ;
CREATE TABLE IF NOT EXISTS `adds_filters` (
`addfilterid` int(11) NOT NULL AUTO_INCREMENT,
`addid` int(11) NOT NULL,
`filterid` int(11) NOT NULL,
PRIMARY KEY (`addfilterid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=45 ;
I have the following sql query that works like a charm, but I need to modify it:
SELECT DISTINCT a.addid
, a.memberid
, a.isnew
, a.catid
, a.manufacturerid
, a.modelid
, a.colorid
, a.geographicareaid
, a.addtypeid
, a.addcreatedon
, a.addvalidfrom
, a.addvaliduntil
, a.addcreatedfromip
, a.yearofmanufacturing
, a.monthofmanufacturing
, a.hoursused
, a.cc2
, a.horsepowers
, a.metalic
, a.isdamaged
, a.price
, a.hasvat
, a.canbenegotiated
, a.addtitle
, a.addtext
, a.youtubevideo
, a.visible
, a.ff1
, a.ff2
, a.ff3
, a.ff4
FROM adds a
JOIN adds_filters f
ON f.addid = a.addid
WHERE a.catid = 1
AND a.manufacturerid = 1
AND f.filterid IN (67,158)
My problem here is the following: if I add one more filter, (example 162) query should returns no results, since there is no add that has all 3 filters. Current query returns 3 rows, which all have the 67 and 158. Anyone can tell me how can I get the desired result?
Regards, John
Here is SQLfiddle
You should understand, that you gonna need to dynamicaly add the subqueries to each checked filterid.
Here is the query (you also can play with filterids in the main SELECT:
SELECT t1.*, t2.filterid as filterid2
FROM
(
SELECT DISTINCT a.*,
f.`filterid`
FROM adds a
JOIN adds_filters f
ON a.`addid` = f.`addid`
WHERE a.`catid` = 1
AND a.`manufacturerid` = 1
AND f.`filterid` = 67
) t1
JOIN
(
SELECT DISTINCT a.`addid`,
f.`filterid`
FROM adds a
JOIN adds_filters f
ON a.`addid` = f.`addid`
WHERE a.`catid` = 1
AND a.`manufacturerid` = 1
AND f.`filterid` = 158
) t2
ON t1.addid = t2.addid
JOIN
(
SELECT DISTINCT a.`addid`,
f.`filterid`
FROM adds a
JOIN adds_filters f
ON a.`addid` = f.`addid`
WHERE a.`catid` = 1
AND a.`manufacturerid` = 1
AND f.`filterid` = 162
) t3
ON t1.addid = t3.addid;
You should be able to simply change your join to the adds_filters component
FROM adds a
JOIN ( select addid
from adds_filters
where filterid in ( 67, 158, 162 )
group by addid
having count(*) = 3 ) f
ON f.addid = a.addid
WHERE a.catid = 1
AND a.manufacturerid = 1
By changing to a prequery of only those AddIDs that have all 3 components (via group by and having), it will only return those valid AddIDs
I would tend to go with the suggestion by DRapp, but if there are issues knowing how many filters there are in advance when building the SQL then another possibility would me one inner join per filter.
SELECT DISTINCT a.addid
, a.memberid
, a.isnew
, a.catid
, a.manufacturerid
, a.modelid
, a.colorid
, a.geographicareaid
, a.addtypeid
, a.addcreatedon
, a.addvalidfrom
, a.addvaliduntil
, a.addcreatedfromip
, a.yearofmanufacturing
, a.monthofmanufacturing
, a.hoursused
, a.cc2
, a.horsepowers
, a.metalic
, a.isdamaged
, a.price
, a.hasvat
, a.canbenegotiated
, a.addtitle
, a.addtext
, a.youtubevideo
, a.visible
, a.ff1
, a.ff2
, a.ff3
, a.ff4
FROM adds a
INNER JOIN adds_filters f1
ON f1.addid = a.addid AND f1.filterid = 67
INNER JOIN adds_filters f2
ON f2.addid = a.addid AND f2.filterid = 158
INNER JOIN adds_filters f3
ON f3.addid = a.addid AND f3.filterid = 162
WHERE a.catid = 1
AND a.manufacturerid = 1

How to generate random codes, and run an sql multiple times

I have a query I need to run and I have 2 problems.
first here is my query:
INSERT INTO `anzie_oscommerce`.`discount_codes` (
`discount_codes_id` ,
`discount_description` ,
`products_id` ,
`categories_id` ,
`manufacturers_id` ,
`excluded_products_id` ,
`customers_id` ,
`orders_total` ,
`order_info` ,
`exclude_specials` ,
`discount_codes` ,
`discount_values` ,
`minimum_order_amount` ,
`expires_date` ,
`number_of_orders` ,
`number_of_use` ,
`number_of_products` ,
`status`
)
VALUES (
'' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1'
);
The first problem is I need to generate the random code which I am trying to do with the uniqid function I took from php but I know that is not possible. Is there a way to do something similar in sql?
The second problem is I need to run this 250 times to generate 250 different discount codes. Is there a quick way to run an sql multiple times?
For the first problem: it depends on the database you're using. Mysql has a rand() function: https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand
For the second: 250 is not many for a database - just putting it in a php for loop would most likely be fine.
I like the answer sonofagun answer. Another trick is to select from a dummy table 250 times.
INSERT INTO `anzie_oscommerce`.`discount_codes` (
`discount_codes_id` ,
`discount_description` ,
`products_id` ,
`categories_id` ,
`manufacturers_id` ,
`excluded_products_id` ,
`customers_id` ,
`orders_total` ,
`order_info` ,
`exclude_specials` ,
`discount_codes` ,
`discount_values` ,
`minimum_order_amount` ,
`expires_date` ,
`number_of_orders` ,
`number_of_use` ,
`number_of_products` ,
`status`
)
(select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all
select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all
select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all
select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all
...however many times
);