how to group by two fileds in datatable in vb.net - mysql

I have a sql statment I get the data from it to the datatable but what I need is filtering the data by dataview and create group y with sum the quantity for each group:
SELECT
FatoraReso as xAcc,
AccName AS xAccName,
FatoraDate AS xDate,
FatoraProduct as xProdID,
ProductName AS xProdName,
FatoraPurPrice as xPrice,
sum(FatoraQuan) as xQuan,
COUNT(FatoraID) AS xCarCount
from tblfatora
INNER JOIN tblaccounts ON tblaccounts.AccID = tblfatora.FatoraReso
INNER JOIN tblproducts ON tblproducts.ProductID = tblfatora.FatoraProduct
GROUP BY xAcc,xDate,xProdID,xPrice
UNION ALL
SELECT
FatoraCustomer as xAcc,
AccName AS xAccName,
FatoraDate AS xDate,
FatoraProduct as xProdID,
ProductName AS xProdName,
FatoraSalePrice as xPrice,
sum(FatoraQuan) as xQuan,
COUNT(FatoraID) AS xCarCount
from tblfatora
INNER JOIN tblaccounts ON tblaccounts.AccID = tblfatora.FatoraCustomer
INNER JOIN tblproducts ON tblproducts.ProductID = tblfatora.FatoraProduct
GROUP BY xAcc,xDate,xProdID,xPrice
ORDER BY xProdID,xPrice
I made a filter by the xAcc and xDate and then I didn't know how to apply group by with get the sum for each group.
I saw some solutions about using The LINQ but really I don't anything about LINQ.
so can help me please.
the final table that I want is:
+---------+--------+-------+-----------+
| xProdID | xPrice | xQuan | xCarCount |
+---------+--------+-------+-----------+
| 1 | 55 | 10 | 2 |
+---------+--------+-------+-----------+
| 1 | 60 | 15 | 1 |
+---------+--------+-------+-----------+
| 2 | 150 | 12 | 3 |
+---------+--------+-------+-----------+
| 2 | 155 | 11 | 2 |
+---------+--------+-------+-----------+
tblfatora:
CREATE TABLE `tblfatora` (
`FatoraID` bigint(20) NOT NULL,
`FatoraRef` bigint(20) NOT NULL,
`FatoraCode` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`FatoraDate` date NOT NULL,
`FatoraProduct` int(11) NOT NULL,
`FatoraQuan` double NOT NULL DEFAULT '0',
`FatoraReso` int(11) NOT NULL,
`FatoraPurPrice` double NOT NULL DEFAULT '0',
`FatoraPurTotal` double NOT NULL DEFAULT '0',
`FatoraCustomer` int(11) NOT NULL,
`FatoraSalePrice` double NOT NULL DEFAULT '0',
`FatoraDis` double NOT NULL DEFAULT '0',
`FatoraPlus` double NOT NULL DEFAULT '0',
`FatoraSaleTotal` double NOT NULL DEFAULT '0',
`FatoraDriverPayStatus` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`FatoraDriver` int(11) NOT NULL,
`FatoraCarNo` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`FatoraDriverCost` double NOT NULL DEFAULT '0',
`FatoraDriverCostTotal1` double NOT NULL DEFAULT '0',
`FatoraDriverCostTotal2` double NOT NULL DEFAULT '0',
`FatoraDriverPrice` double NOT NULL DEFAULT '0',
`FatoraDetails1` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`FatoraDetails2` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`FatoraDetails3` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`FatoraPalletQuan` double NOT NULL DEFAULT '0',
`FatoraPalletPrice` double NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPACT;
tblFatoraData:
INSERT INTO `tblfatora` (`FatoraID`, `FatoraRef`, `FatoraCode`, `FatoraDate`,
`FatoraProduct`, `FatoraQuan`, `FatoraReso`, `FatoraPurPrice`,
`FatoraPurTotal`, `FatoraCustomer`, `FatoraSalePrice`, `FatoraDis`,
`FatoraPlus`, `FatoraSaleTotal`, `FatoraDriverPayStatus`, `FatoraDriver`,
`FatoraCarNo`, `FatoraDriverCost`, `FatoraDriverCostTotal1`,
`FatoraDriverCostTotal2`, `Fato`raDriverPrice`, `FatoraDetails1`,
`FatoraDetails2`, `FatoraDetails3`, `FatoraPalletQuan`, `FatoraPalletPrice`)
VALUES
(1, 202010180304112, '', '2020-10-01', 41, 31, 112, 71, 2201, 93, 71, 0, 0,
2201, 'Paid', 128, '135538', 0, 0, 0, 1, '', '', '', 0, 0),
(2, 202010180720343, '', '2020-10-01', 43, 40, 112, 61, 2440, 83, 68000, 0,
0, 2720000, 'Paid', 129, '', 0, 0, 0, 1, '', '', '', 0, 0),
(3, 202010180807273, '', '2020-10-01', 43, 34, 112, 61, 2074, 341, 72000, 0,
0, 2448000, 'Paid', 130, '8142', 0, 0, 0, 1, '', '', '', 0, 0),
(4, 202010180819273, '', '2020-10-01', 50, 40, 114, 70, 2800, 76, 70, 0, 0,
2800, 'Paid', 131, '', 0, 0, 0, 1250, '', '', '', 0, 0),
(5, 202010180821373, '', '2020-10-01', 55, 39.22, 114, 66, 2588.52, 55, 66,
0, 0, 2588.52, 'Paid', 132, '', 0, 0, 0, 1250, '', '', '', 0, 0),
(6, 202010180823183, '', '2020-10-01', 50, 38, 114, 70, 2660, 360, 70, 0, 0,
2660, 'Paid', 133, '', 0, 0, 0, 1, '', '', '', 0, 0),
(7, 202010180825173, '', '2020-10-01', 50, 39, 114, 70, 2730, 67, 64, 0, 14,
2510, 'Paid', 134, '', 0, 0, 0, 1250, '', '', '', 0, 0),
(8, 202010180832333, '', '2020-10-02', 48, 31, 113, 63, 1953, 64, 56, 0, 0,
1736, 'Paid', 135, '', 0, 0, 0, 1240, '', '', '', 0, 0),
(9, 202010180833593, '', '2020-10-01', 48, 35, 113, 63, 2205, 82, 63, 0, 0,
2205,
'Paid', 136, '', 0, 0, 0, 1, '', '1', '', 0, 0),
(10, 202010180838003, '', '2020-10-01', 35, 35.46, 115, 57, 2021.22, 53, 56,
0, 0, 1985.76, 'Paid', 137, '135280', 0, 0, 0, 1240, '', '', '', 0, 0),
(11, 202010180841213, '', '2020-10-02', 43, 33, 112, 61, 2013, 79, 58, 0, 0,
1914, 'Paid', 138, '', 0, 0, 0, 1240, '', '', '', 0, 0),
(12, 202010180843373, '', '2020-10-02', 43, 39, 112, 61, 2379, 84, 70000, 0,
0, 2730000, 'Paid', 139, '10978', 0, 0, 0, 1, '', '', '', 0, 0),
(13, 202010180846253, '', '2020-10-02', 43, 39, 112, 61, 2379, 225, 56, 0, 0,
2184, 'Paid', 140, '9705', 0, 0, 0, 1240, '', '', '', 0, 0),
(14, 202010180847593, '', '2020-10-02', 43, 40, 112, 61, 2440, 344, 61, 0, 0,
2440, 'Paid', 141, '97464', 0, 0, 0, 1, '', '', '', 0, 0),
(15, 202010180849563, '', '2020-10-02', 43, 36, 112, 61, 2196, 73, 57, 0, 0,
2052, 'Paid', 142, '', 0, 0, 0, 1240, '', '', '', 0, 0),
(16, 202010180852113, '', '2020-10-02', 43, 39, 112, 61, 2379, 357, 61, 0, 0,
2379, 'Paid', 143, '151957', 0, 0, 0, 1, '', '', '', 0, 0)

You can use every Query as basis (subquery) too do more calculations
SELECT
xProdID,
xPrice,
xProdName,
SUM(xQuan) AS xQuan,
SUM(xCarCount) AS xCarCount
FROM (SELECT
FatoraReso AS xAcc,
AccName AS xAccName,
FatoraDate AS xDate,
FatoraProduct AS xProdID,
ProductName AS xProdName,
FatoraPurPrice AS xPrice,
SUM(FatoraQuan) AS xQuan,
COUNT(FatoraID) AS xCarCount
FROM
tblfatora
INNER JOIN
tblaccounts ON tblaccounts.AccID = tblfatora.FatoraReso
INNER JOIN
tblproducts ON tblproducts.ProductID = tblfatora.FatoraProduct
GROUP BY xAcc , xDate , xProdID , xPrice
UNION ALL SELECT
FatoraCustomer AS xAcc,
AccName AS xAccName,
FatoraDate AS xDate,
FatoraProduct AS xProdID,
ProductName AS xProdName,
FatoraSalePrice AS xPrice,
SUM(FatoraQuan) AS xQuan,
COUNT(FatoraID) AS xCarCount
FROM
tblfatora
INNER JOIN
tblaccounts ON tblaccounts.AccID = tblfatora.FatoraCustomer
INNER JOIN
tblproducts ON tblproducts.ProductID = tblfatora.FatoraProduct
GROUP BY xAcc , xDate , xProdID , xPrice) t1
GROUP BY
xProdID , xPrice
ORDER BY xProdID , xPrice
As i wrote in my comment.
''Isee two possibility to get only the dates for one or more date.
The selection depends whetger you have a fast connection and a fast server.
Solution 1;:
You get all data into a table and have a dataview t filter your wanted dates.
then have a Sub which sums up the data according to xProdID , xPrice.
That is suitable if you a slow connection or a slow database server, so that the computer does it all on client side.
Solution 2
You send to the server a new SELECT as posted abouve only you add a where clause which only selects the appropriate dates before the final GROUP BY and SUM.
this works just fine, when all is quite fast.
The aggregation functions lose data, because it has only the max date, this may be enugh, but i don#t believe that it will suffice

Related

Laravel 7 eloquent join with relavent record of right table

I am fetching product price after applying catalog rules on products, I build a sql query and trying to do this query in Laravel 7 with Eloquent but unable to get relavent record from catalog_rule join because catalog_rule may has multiple records for a product and i must to pick most relavent and recent record including override ='yes'.
SQL Query:
SELECT products.*, hike_rule.hike_type, hike_rule.hike_amount, discount_rule.hike_amount as discount
IF(hike_rule.hike_amount > 0,
IF(hike_rule.hike_type = 'percent'),
#product_price := (products.price + products.price*hike_rule.hike_amount/100)
,
#product_price := (products.price + hike_rule.hike_amount)
,
#product_price := products.price) as product_price,
IF(discount > 0,
#product_sale_price := (#product_price + #product_price*discount/100)
,
#product_sale_price := #product_price
) as product_sale_price
FROM products
LEFT JOIN (
SELECT * FROM catalog_rule_products,catalog_rule where catalog_rule_products.rule_id = catalog_rule.rule_id and catalog_rule.status = 'active' and (catalog_rule.from_date != "0000-00-00" and catalog_rule.from_date <= NOW() ) and (catalog_rule.to_date != "0000-00-00" and catalog_rule.to_date >= NOW() ) and catalog_rule.rule_type = 'price_hike'
order by IF(override ='yes', 1, 0),rule_id desc
) hike_rule ON (hike_rule.product_id = products.product_id)
LEFT JOIN (
SELECT *
FROM catalog_rule_products,catalog_rule
where catalog_rule_products.rule_id = catalog_rule.rule_id and catalog_rule.status = 'active' and (catalog_rule.from_date != "0000-00-00" and catalog_rule.from_date <= NOW() ) and (catalog_rule.to_date != "0000-00-00" and catalog_rule.to_date >= NOW() ) and catalog_rule.rule_type = 'price_discount' order by IF(override ='yes', 1, 0),rule_id desc
) discount_rule ON (discount_rule.product_id = products.product_id)
WHERE products.category_id = 3 group by products.product_id
order by product_sale_price desc
I have pagination, searching, sorting too with products and other are working.
Table structure:
products
product_id , sku, category_id, qty, price
catalog_rule
CREATE TABLE `catalog_rule` (
`rule_id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`rule_type` enum('price_discount','price_hike') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'price_discount',
`description` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`from_date` date DEFAULT NULL,
`to_date` date DEFAULT NULL,
`is_active` enum('enabled','disabled') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'disabled',
`conditions_type` enum('category','price','sku') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`sku` mediumtext COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`category_slug` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`sort_order` int(11) NOT NULL DEFAULT 0,
`hike_amount` decimal(8,2) NOT NULL,
`hike_type` enum('percent','fixed') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'percent',
`country_code` varchar(4) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`override` enum('yes','no') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no',
`skip_products` enum('yes','no') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `catalog_rule` (`rule_id`, `name`, `rule_type`, `description`, `from_date`, `to_date`, `is_active`, `conditions_type`, `sku`, `category_slug`, `sort_order`, `hike_amount`, `hike_type`, `country_code`, `created_at`, `updated_at`, `override`, `skip_products`) VALUES
(3, 'new rule', 'price_discount', 'test', '2021-10-07', '2022-01-31', 'enabled', 'category', '', 'gowns', 0, '15.00', 'percent', 'all', '2021-10-06 07:29:43', '2022-01-31 08:52:49', 'no', 'no'),
(4, 'test2 rule', 'price_hike', NULL, '2021-12-01', '2022-01-31', 'enabled', 'category', '', 'gowns', 0, '70.00', 'percent', 'all', '2022-01-31 08:49:20', '2022-01-31 08:52:03', 'no', 'no'),
(5, 'test2 rule hike jutti', 'price_hike', NULL, '0000-00-00', '0000-00-00', 'enabled', 'category', 'a:4:{i:0;s:12:\"MBAG2110AV20\";i:1;s:12:\"MBAG2112CMR6\";i:2;s:11:\"MFM2006MCA2\";i:3;s:19:\"MLADIES-JUT2108BAW5\";}', 'ladies-juttis', 0, '30.00', 'percent', 'all', '2022-03-04 12:53:02', '2022-03-08 11:10:17', 'no', 'yes'),
(6, 'shoes products hike', 'price_hike', NULL, '0000-00-00', '0000-00-00', 'enabled', 'sku', 'a:2:{i:0;s:19:\"MLADIES-JUT2108AV0J\";i:1;s:19:\"MLADIES-JUT2108AV26\";}', NULL, 0, '40.00', 'percent', 'all', '2022-03-08 11:12:48', '2022-03-08 11:12:48', 'no', 'no'),
(7, 'shoes products1', 'price_hike', NULL, '0000-00-00', '0000-00-00', 'enabled', 'sku', 'a:1:{i:0;s:19:\"MLADIES-JUT2108BAW5\";}', NULL, 0, '35.00', 'percent', 'all', '2022-03-08 11:15:00', '2022-03-08 11:41:39', 'no', 'no'),
(8, 'hand bags 25% hike', 'price_hike', NULL, '0000-00-00', '0000-00-00', 'enabled', 'category', '', 'ladies-bags', 0, '25.00', 'percent', 'all', '2022-03-08 11:15:54', '2022-03-12 02:12:52', 'no', 'no'),
(9, 'saree 30% hike', 'price_hike', NULL, '0000-00-00', '0000-00-00', 'disabled', 'category', '', 'sarees', 0, '30.00', 'percent', 'all', '2022-03-08 11:44:51', '2022-03-11 05:06:08', 'no', 'no'),
( 10, 'Saree 40% hike', 'price_hike', NULL, '2022-03-04', '2022-03-11', 'disabled', 'category', '', 'sarees', 0, '40.00', 'percent', 'all', '2022-03-08 14:21:09', '2022-03-11 05:05:41', 'no', 'no'),
(11, 'hike 25% on sarees', 'price_hike', NULL, '0000-00-00', '0000-00-00', 'enabled', 'category', '', 'sarees', 0, '25.00', 'percent', 'all', '2022-03-09 04:29:00', '2022-03-11 06:12:35', 'yes', 'no'),
(12, 'discount 30% saree', 'price_discount', NULL, '0000-00-00', '0000-00-00', 'disabled', 'category', '', 'sarees', 0, '30.00', 'fixed', 'all', '2022-03-09 06:03:26', '2022-03-11 05:06:49', 'no', 'no'),
(13, 'discount 40% saree', 'price_discount', NULL, '0000-00-00', '0000-00-00', 'disabled', 'category', '', 'sarees', 0, '40.00', 'percent', 'all', '2022-03-09 10:02:30', '2022-03-09 10:02:30', 'yes', 'no'),
(14, 'shirts 10% discount', 'price_discount', NULL, '0000-00-00', '0000-00-00', 'enabled', 'category', '', 'shirts', 0, '10.00', 'percent', 'all', '2022-03-10 08:48:42', '2022-03-11 12:01:48', 'no', 'no');
Catalog_rule_products
CREATE TABLE `catalog_rule_products` (
`id` bigint(20) UNSIGNED NOT NULL,
`rule_id` int(10) UNSIGNED NOT NULL,
`product_id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO catalog_rule_products (id, rule_id, product_id) VALUES
(2, 7, 2160),
(1045, 13, 176),
(1046, 13, 178),
(1047, 13, 179),
(1048, 13, 230),
(1049, 13, 231),
(1050, 13, 232),
(1051, 13, 233),
(1052, 13, 234),
(1053, 13, 235),
(1054, 13, 236),
(1055, 13, 237),
(1056, 13, 238),
(1057, 13, 239),
(1058, 13, 240),
(1059, 13, 241),
(1060, 13, 242),
(1061, 13, 243),
(1062, 13, 244),
(1063, 13, 245),
(1064, 13, 246),
(1065, 13, 247),
(1066, 13, 248),
(1067, 13, 249),
(1068, 13, 250),
(1069, 13, 251),
(1070, 13, 252),
(1071, 13, 253),
(1072, 13, 254),
(1073, 13, 255),
(1074, 13, 256),
(1075, 13, 257),
(1076, 13, 258),
(1077, 13, 259),
(1078, 13, 260),
(1079, 13, 261),
(1080, 13, 262),
(1081, 13, 263),
(1082, 13, 264),
(1083, 13, 265),
(1084, 13, 266),
(1085, 13, 267),
(1086, 13, 268),
(1087, 13, 269),
(1088, 13, 270),
(1089, 13, 271),
(1090, 13, 272),
(1091, 13, 273),
(1092, 13, 274),
(1093, 13, 275),
(1094, 13, 276),
(1095, 13, 277),
(1096, 13, 278),
(1097, 13, 279),
(1098, 13, 280),
(1099, 13, 281),
(1100, 13, 282),
(1101, 13, 283),
(1102, 13, 284),
(1103, 13, 285),
(1104, 13, 286),
(1105, 13, 287),
(1106, 13, 288),
(1107, 13, 290),
(1108, 13, 291),
(1109, 13, 292),
(1110, 13, 294),
(1111, 13, 295),
(1112, 13, 305),
(1113, 13, 307),
(1114, 13, 308),
(1115, 13, 309),
(1116, 13, 310),
(1117, 13, 311),
(1118, 13, 312),
(1119, 13, 313),
(1120, 13, 314),
(1121, 13, 316),
(1122, 13, 318),
(1123, 13, 320),
(1124, 13, 322),
(1125, 13, 323),
(1126, 13, 325),
(1127, 13, 326),
(1128, 13, 327),
(1129, 13, 334),
(1130, 13, 457),
(1131, 13, 458),
(1132, 13, 459),
(1133, 13, 460),
(1134, 13, 461),
(1135, 13, 462),
(1136, 13, 463),
(1137, 13, 464),
(1138, 13, 465),
(1139, 13, 468),
(1140, 13, 469),
(1141, 13, 472),
(1142, 13, 474),
(1143, 13, 475),
(1144, 13, 480),
(1145, 13, 482),
(1146, 13, 484),
(1147, 13, 485),
(1148, 13, 2135),
(1149, 13, 2135),
(1150, 13, 2135),
(1151, 13, 2135),
(1152, 13, 2136),
(1153, 13, 2137),
(1154, 13, 2138),
(1155, 13, 2144),
(1156, 13, 2148),
(1157, 13, 2151),
(1158, 13, 2170),
(1159, 13, 2170),
(1160, 13, 2174),
(1972, 11, 176),
(1973, 11, 178),
(1974, 11, 179),
(1975, 11, 230),
(1976, 11, 231),
(1977, 11, 232),
(1978, 11, 233),
(1979, 11, 234),
(1980, 11, 235),
(1981, 11, 236),
(1982, 11, 237),
(1983, 11, 238),
(1984, 11, 239),
(1985, 11, 240),
(1986, 11, 241),
(1987, 11, 242),
(1988, 11, 243),
(1989, 11, 244),
(1990, 11, 245),
(1991, 11, 246),
(1992, 11, 247),
(1993, 11, 248),
(1994, 11, 249),
(1995, 11, 250),
(1996, 11, 251),
(1997, 11, 252),
(1998, 11, 253),
(1999, 11, 254),
(2000, 11, 255),
(2001, 11, 256),
(2002, 11, 257),
(2003, 11, 258),
(2004, 11, 259),
(2005, 11, 260),
(2006, 11, 261),
(2007, 11, 262),
(2008, 11, 263),
(2009, 11, 264),
(2010, 11, 265),
(2011, 11, 266),
(2012, 11, 267),
(2013, 11, 268),
(2014, 11, 269),
(2015, 11, 270),
(2016, 11, 271),
(2017, 11, 272),
(2018, 11, 273),
(2019, 11, 274),
(2020, 11, 275),
(2021, 11, 276),
(2022, 11, 277),
(2023, 11, 278),
(2024, 11, 279),
(2025, 11, 280),
(2026, 11, 281),
(2027, 11, 282),
(2028, 11, 283),
(2029, 11, 284),
(2030, 11, 285),
(2031, 11, 286),
(2032, 11, 287),
(2033, 11, 288),
(2034, 11, 290),
(2035, 11, 291),
(2036, 11, 292),
(2037, 11, 294),
(2038, 11, 295),
(2039, 11, 305),
(2040, 11, 307),
(2041, 11, 308),
(2042, 11, 309),
(2043, 11, 310),
(2044, 11, 311),
(2045, 11, 312),
(2046, 11, 313),
(2047, 11, 314),
(2048, 11, 316),
(2049, 11, 318),
(2050, 11, 320),
(2051, 11, 322),
(2052, 11, 323),
(2053, 11, 325),
(2054, 11, 326),
(2055, 11, 327),
(2056, 11, 334),
(2057, 11, 457),
(2058, 11, 458),
(2059, 11, 459),
(2060, 11, 460),
(2061, 11, 461),
(2062, 11, 462),
(2063, 11, 463),
(2064, 11, 464),
(2065, 11, 465),
(2066, 11, 468),
(2067, 11, 469),
(2068, 11, 472),
(2069, 11, 474),
(2070, 11, 475),
(2071, 11, 480),
(2072, 11, 482),
(2073, 11, 484),
(2074, 11, 485),
(2075, 11, 2135),
(2076, 11, 2135),
(2077, 11, 2135),
(2078, 11, 2135),
(2079, 11, 2136),
(2080, 11, 2137),
(2081, 11, 2138),
(2082, 11, 2144),
(2083, 11, 2148),
(2084, 11, 2151),
(2085, 11, 2170),
(2086, 11, 2170),
(2087, 11, 2174),
(2089, 14, 2176),
(2090, 8, 2173),
(2091, 8, 2181),
(2092, 8, 2182),
(2093, 8, 2183),
(2094, 8, 2187);

Unable to DATE_SUB correctly in a double inner join

I'm writing a query to update some chained rowsthat looks like this
SELECT T.Id,
T.Id + 1 AS NewID,
T.DifferenceTime,
RAT.AllowedDate,
RAT.ExpirationDate,
DATE_SUB(RAT.AllowedDate, INTERVAL T.DifferenceTime MINUTE) AS NewAllowedDate,
DATE_SUB(RAT.ExpirationDate, INTERVAL T.DifferenceTime MINUTE) AS NewExpiringDate
FROM ROOMS_ACCESS_TOKENS RAT
INNER JOIN (
SELECT T2.*,
ABS(TIMESTAMPDIFF(MINUTE,T2.ExpirationDate,UTC_TIMESTAMP())) AS DifferenceTime
FROM ROOMS_ACCESS_TOKENS RAT
INNER JOIN (
SELECT *
FROM ROOMS_ACCESS_TOKENS
WHERE Expired = 0 AND ExpirationDate > UTC_TIMESTAMP()
) AS T2 ON T2.IdRoom = RAT.IdRoom AND T2.ChainId = RAT.ChainId
WHERE RAT.IdRoom = 1
AND RAT.AccessToken = '5092FFA0B3721AE5EC757649DE983F8020220104215810'
AND RAT.RefId = 'B49F723F2FE0FD38063DA26F3EAEDBED'
AND RAT.KeyCode = '2773217uysagkasd8wqejhjkasdsm'
AND RAT.ExpirationDate > UTC_TIMESTAMP()
AND RAT.Expired = 0
) AS T ON T.IdRoom = RAT.IdRoom
AND T.ChainId = RAT.ChainId
AND T.AccessToken = RAT.AccessToken
AND T.RefId = RAT.RefId
AND T.AllowedDate = RAT.AllowedDate
This suppose to select a row by IdRoom, AccessToken, RefId, KeyCode and be above a certain date and not Expired.
Then get all chainded rows by ChainId and calculate time different between UTC_TIMESTAMP() and row ExpirationDate. (I guess it works till this point)
With that difference in minute, I want to calculate new datetimes but it doesn't work.
I've attached a screenshot with results
As you can see, it looks like NewAllowedDate and NewExpiringDate get calculated only for the first row.. But NewID gets calculated for all of them..
I can't understand where my query is wrong.
Any ideas?
Here the table and some data insert example
CREATE TABLE `ROOMS_ACCESS_TOKENS` ( `Id` int(11) NOT NULL, `IdRoom` int(11) DEFAULT NULL, `AccessToken` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, `RefId` varchar(35) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, `KeyCode` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `Allowed` int(1) NOT NULL, `Used` int(1) NOT NULL, `Expired` int(1) NOT NULL DEFAULT '0', `ChainId` int(11) NOT NULL DEFAULT '1', `StartDate` datetime DEFAULT NULL, `AllowedDate` datetime NOT NULL, `ExpirationDate` datetime DEFAULT NULL, `ResidenceTime` int(5) NOT NULL, `Url` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `ROOMS_ACCESS_TOKENS` (`Id`, `IdRoom`, `AccessToken`, `RefId`, `KeyCode`, `Allowed`, `Used`, `Expired`, `ChainId`, `StartDate`, `AllowedDate`, `ExpirationDate`, `ResidenceTime`, `Url`) VALUES (1, 1, '5092FFA0B3721AE5EC757649DE983F8020220104215810', 'B49F723F2FE0FD38063DA26F3EAEDBED', '2773217uysagkasd8wqejhjkasdsm', 1, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-04 22:30:46', '2022-01-04 23:30:46', 60, '/it'), (2, 1, '9CAB5CABB559260D41366E1041B46D0320220104233046', 'B086A4B3F4996C69B4DBB206C2E0D799', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-04 23:31:46', '2022-01-05 00:31:46', 60, '/it'), (3, 1, '3A2AE9CAC195B9938D25AE654790FAE020220104233046', 'E756AF83048259114F7E0BA04FFA799E', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-05 00:32:46', '2022-01-05 01:32:46', 60, '/it'), (4, 1, '17267FAC80875252F5F1E2585D078B1D20220104233046', '62143086CF25D276FD4C6D4465BDD41E', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-05 01:33:46', '2022-01-05 02:33:46', 60, '/it'), (5, 1, '39F47036B85694A231668BB8DFBF3CD120220104233046', 'C2C8F545B9FF7C59D50958C14EE61BF7', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-05 02:34:46', '2022-01-05 03:34:46', 60, '/it'), (6, 1, '61919A70C0D7AD4FB642BE1A3D6FE10420220104233046', 'EB1F2AF642C779B29F89023260A3AC94', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-05 03:35:46', '2022-01-05 04:35:46', 60, '/it'), (7, 1, '62BCFCCAC7F2EAFD5B1E06B32A810C1420220104233046', 'DDFB911F2197B50861AABD77005D9946', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-05 04:36:46', '2022-01-05 05:36:46', 60, '/it'), (8, 1, '6F72CCB6F3DF8F90C1A2911A7F1E097720220104233046', 'CCD116F4D4EFA9AE7D9B8DA780C5A73E', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-05 05:37:46', '2022-01-05 06:37:46', 60, '/it'), (9, 1, 'E8610F5C7551DA2695360B77431BBB1020220104233046', '49ABCCBDF6FC02FF290357B6A29DB2FC', '2773217uysagkasd8wqejhjkasdsm', 0, 1, 0, 1, '2022-01-04 22:30:46', '2022-01-05 06:38:46', '2022-01-05 07:38:46', 60, '/it'), (10, 1, '78BFEAF3EC52298B9EB5CDA8920168FE20220104233046', '755E481F29003C1EDC3A682D5037EF9F', '2773217uysagkasd8wqejhjkasdsm', 0, 0, 0, 1, '2022-01-04 22:30:46', '2022-01-05 07:39:46', '2022-01-05 08:39:46', 60, '/it');
ALTER TABLE `ROOMS_ACCESS_TOKENS` ADD PRIMARY KEY (`Id`), ADD KEY `IX_ACCESS_TOKEN` (`AccessToken`), ADD KEY `KeyCode` (`KeyCode`), ADD KEY `RefId` (`RefId`), ADD KEY `IdRoom` (`IdRoom`), ADD KEY `Allowed` (`Allowed`), ADD KEY `Used` (`Used`), ADD KEY `Expired` (`Expired`);
ALTER TABLE `ROOMS_ACCESS_TOKENS` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
These sound redundant. The former one is dynamic; the latter one is potentially not-yet-set.
AND RAT.ExpirationDate > UTC_TIMESTAMP()
AND RAT.Expired = 0
I do not understand your date arithmetic, especially since the columns, being DATETIME, have 'second' resolution, yet the arithmetic involved 'MINUTEs'.
What is the meaning of "ABS" in ABS(TIMESTAMPDIFF(MINUTE,T2.ExpirationDate, UTC_TIMESTAMP())) AS DifferenceTime
Please do not use the same alias twice; it confuses me, and maybe the parser. (I am thinking of RAT, at least.)

Nested MySQL query hanging

I am working with the flights test data set.
CREATE TABLE IF NOT EXISTS `flights` (
`flightsKey` int(11) NOT NULL AUTO_INCREMENT,
`sno` varchar(10) DEFAULT NULL,
`year` int(4) DEFAULT NULL,
`month` int(2) DEFAULT NULL,
`day` varchar(10) DEFAULT NULL,
`dep_time` int(4) DEFAULT NULL,
`sched_dep_time` int(4) DEFAULT NULL,
`dep_delay` int(10) DEFAULT NULL,
`arr_time` int(4) DEFAULT NULL,
`sched_arr_time` int(4) DEFAULT NULL,
`arr_delay` int(10) DEFAULT NULL,
`carrier` varchar(2) DEFAULT NULL,
`flight` varchar(3) DEFAULT NULL,
`tailnum` varchar(10) NOT NULL,
`origin` varchar(3) DEFAULT NULL,
`dest` varchar(3) DEFAULT NULL,
`air_time` int(10) DEFAULT NULL,
`distance` int(10) DEFAULT NULL,
`hour` int(2) DEFAULT NULL,
`minute` int(3) DEFAULT NULL,
`fullDate` varchar(12) DEFAULT NULL,
PRIMARY KEY (`flightsKey`),
KEY `origin` (`origin`),
KEY `carrier` (`carrier`),
KEY `dest` (`dest`),
KEY `tailnum` (`tailnum`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=336868 ;
--
-- Dumping data for table `flights`
--
INSERT INTO `flights` (`flightsKey`, `sno`, `year`, `month`, `day`, `dep_time`, `sched_dep_time`, `dep_delay`, `arr_time`, `sched_arr_time`, `arr_delay`, `carrier`, `flight`, `tailnum`, `origin`, `dest`, `air_time`, `distance`, `hour`, `minute`, `fullDate`) VALUES
(1, '1', 2013, 1, '1', 517, 515, 2, 830, 819, 11, 'UA', '154', 'N14228', 'EWR', 'IAH', 227, 1400, 5, 15, '0000-00-00'),
(2, '2', 2013, 1, '1', 533, 529, 4, 850, 830, 20, 'UA', '171', 'N24211', 'LGA', 'IAH', 227, 1416, 5, 29, '0000-00-00'),
(3, '3', 2013, 1, '1', 542, 540, 2, 923, 850, 33, 'AA', '114', 'N619AA', 'JFK', 'MIA', 160, 1089, 5, 40, '0000-00-00'),
(4, '4', 2013, 1, '1', 544, 545, -1, 1004, 1022, -18, 'B6', '725', 'N804JB', 'JFK', 'BQN', 183, 1576, 5, 45, '0000-00-00'),
(5, '5', 2013, 1, '1', 554, 600, -6, 812, 837, -25, 'DL', '461', 'N668DN', 'LGA', 'ATL', 116, 762, 6, 0, '0000-00-00'),
(6, '6', 2013, 1, '1', 554, 558, -4, 740, 728, 12, 'UA', '169', 'N39463', 'EWR', 'ORD', 150, 719, 5, 58, '0000-00-00'),
(7, '7', 2013, 1, '1', 555, 600, -5, 913, 854, 19, 'B6', '507', 'N516JB', 'EWR', 'FLL', 158, 1065, 6, 0, '0000-00-00'),
(8, '8', 2013, 1, '1', 557, 600, -3, 709, 723, -14, 'EV', '570', 'N829AS', 'LGA', 'IAD', 53, 229, 6, 0, '0000-00-00'),
(9, '9', 2013, 1, '1', 557, 600, -3, 838, 846, -8, 'B6', '79', 'N593JB', 'JFK', 'MCO', 140, 944, 6, 0, '0000-00-00'),
(10, '10', 2013, 1, '1', 558, 600, -2, 753, 745, 8, 'AA', '301', 'N3ALAA', 'LGA', 'ORD', 138, 733, 6, 0, '0000-00-00');
I can get the query working by using views but I am trying to figure out what is causing my nested query to hang
This works without problem. Lets call it query 1:
SELECT carrier FROM flights GROUP BY carrier HAVING COUNT(*) <5000
it produces the following list:
('AS', 'F9','FL', 'HA', 'OO', 'YV')
This also works without problem. lets call it query 2.
SELECT origin, AVG(dep_delay) FROM flights
WHERE carrier IN ('AS', 'F9','FL', 'HA', 'OO', 'YV')
GROUP BY origin
However, when you use the query 1 as in inner query in query 2, it gets stuck:
SELECT origin, AVG(dep_delay) FROM flights
WHERE carrier IN (SELECT carrier FROM flights GROUP BY carrier HAVING COUNT(*) <5000)
GROUP BY origin
I also tried this and it worked without a hitch. I created a view for inner query:
CREATE view smallCarriers AS
SELECT carrier FROM flights GROUP BY carrier HAVING COUNT(*) <5000
Then I used the view as an inner query in the nested query:
SELECT origin, AVG(dep_delay) FROM flights
WHERE carrier IN (SELECT * FROM smallCarriers)
GROUP BY origin
Basically everything worked except for the explicit nested query.
I am running Mysql version 5.5.62 on Ubuntu 14.04. I am running these queries in phpmyadmin and the status of the query says "sending data" when it hangs.
I have included a link to the SQL fiddle here:
http://sqlfiddle.com/#!9/605236/5
It seems to work - so my question is why?
The actual table has 336776 rows. I tried both InnoDB and MyISAM thinking something was going on with the way the referential integrity was setup but I still have the same issue. What about this query causes the script to hang?
note - I have also tried the query from the mysql shell directly with the same result.
I have added the EXPLAIN result from the query which hangs:
mysql> EXPLAIN SELECT origin, AVG(dep_delay) FROM flights WHERE carrier IN (SELECT carrier FROM flights GROUP BY carrier HAVING COUNT(*) <5000) GROUP BY origin;
+----+--------------------+---------+-------+---------------+---------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+---------+-------+---------------+---------+---------+------+--------+-------------+
| 1 | PRIMARY | flights | index | NULL | origin | 12 | NULL | 337143 | Using where |
| 2 | DEPENDENT SUBQUERY | flights | index | NULL | carrier | 9 | NULL | 42183 | Using index |
+----+--------------------+---------+-------+---------------+---------+---------+------+--------+-------------+
2 rows in set (0.01 sec)

Nested SELECT + INNER JOIN

First table
CREATE TABLE IF NOT EXISTS `city_node` (
`node_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
`parent_node_id` int(10) unsigned NOT NULL DEFAULT '0',
`lft` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Nested set info ''left'' value',
`rgt` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Nested set info ''right'' value',
`depth` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Depth = 0: no parent',
PRIMARY KEY (`node_id`),
KEY `parent_node_id` (`parent_node_id`),
KEY `lft` (`lft`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=26;
And data
INSERT INTO `city_node` (`node_id`, `title`, `parent_node_id`, `lft`, `rgt`, `depth`) VALUES
(1, 'Great Britain', 0, 1, 20, 0),
(3, 'England', 1, 2, 9, 1),
(7, 'Scotland', 1, 16, 19, 1),
(8, 'Edinburgh', 7, 17, 18, 2),
(9, 'Wales', 1, 10, 15, 1),
(10, 'Cardiff', 9, 11, 12, 2),
(11, 'London', 3, 3, 4, 2),
(12, 'Birmingham', 3, 5, 6, 2),
(13, 'Germany', 0, 21, 26, 0),
(14, 'Stuttgart', 13, 22, 23, 1),
(15, 'Newport', 9, 13, 14, 2),
(16, 'Munich', 13, 24, 25, 1),
(17, 'Israel', 0, 27, 32, 0),
(18, 'Tel Aviv', 17, 28, 29, 1),
(19, 'Ashdod', 17, 30, 31, 1),
(20, 'USA', 0, 33, 38, 0),
(21, 'New York', 20, 34, 35, 1),
(24, 'Liverpool', 3, 7, 8, 2),
(25, 'Detroit', 20, 36, 37, 1);
Second table
CREATE TABLE IF NOT EXISTS `city_node_entity` (
`node_id` int(10) NOT NULL,
`entity` tinyint(3) unsigned NOT NULL DEFAULT '1',
KEY `node_id` (`node_id`,`entity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
And data
INSERT INTO `city_node_entity` (`node_id`, `entity`) VALUES
(11, 1),
(12, 1),
(16, 1),
(19, 1);
I want to get node with entity 1 and its ancestors, like this
Great Britain
--England
----London
----Birmingham
Germany
--Munich
Israel
--Ashdod
So, my query is
SELECT DISTINCT(node_ext.node_id), node_ext.*
FROM city_node_entity AS entity
LEFT JOIN city_node AS node
ON entity.node_id = node.node_id
LEFT JOIN city_node AS node_ext
ON node_ext.lft <= node.lft AND node_ext.rgt >= node.rgt
WHERE entity.entity = 1
ORDER BY node_ext.lft
But explain shows
-Using where; Using index; Using temporary; Using filesort
Is there any other queries to get same result but with less [EXTRA]?
The only thing you can do for recursive queries is to run it with joins for each parent/child.... because your second table is the actual city name and you want to work backwards you can do it like this... just add more joins till all results are null and you will have yourself the full tree
SELECT node.title AS child, t2.title as parent1, t3.title as parent2, t4.title as parent3
FROM city_node_entity AS entity
LEFT JOIN city_node AS node ON entity.node_id = node.node_id
LEFT JOIN city_node AS t2 ON t2.node_id = node.parent_node_id
LEFT JOIN city_node AS t3 ON t3.node_id = t2.parent_node_id
LEFT JOIN city_node AS t4 ON t4.node_id = t3.parent_node_id;
Fiddle Demo

How to count date difference excluding weekend and holidays in MySQL

I need to count days (business days) between two dates excluding weekend (most important) and holidays
SELECT DATEDIFF(end_date, start_date) from accounts
But, I don't know how am I supposed to do it in MySQL, I found this article Count days between two dates, excluding weekends (MySQL only). I cannot figure out how to functional query in mysql, Can you give some information of how can achieve this with mysql query. If I am missing anything let me know.
[EDIT]
CREATE TABLE `candidatecase` (
`ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Unique ID',
`CreatedBy` int(11) NOT NULL,
`UseraccountID` int(11) NOT NULL COMMENT 'User Account ID',
`ReportReadyID` int(11) DEFAULT NULL COMMENT 'Report Ready ID',
`DateCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date Created',
`InitiatedDate` timestamp NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Date Initiated',
`ActualCompletedDate` timestamp NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Date Completed Case',
`ProjectedCompletedDate` timestamp NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Date Projected Finish',
`CheckpackagesID` int(11) DEFAULT NULL COMMENT 'Default Check Package Auto Assign Once Initiate Start',
`Alacartepackage1` int(11) DEFAULT NULL COMMENT 'Ala carte Request #2',
`Alacartepackage2` int(11) DEFAULT NULL COMMENT 'Ala carte Request #3',
`OperatorID` int(11) NOT NULL COMMENT 'User Account - Operator',
`Status` int(11) NOT NULL COMMENT 'Status',
`caseRef` varchar(100) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=293 ;
--
-- Dumping data for table `candidatecase`
--
INSERT INTO `candidatecase` (`ID`, `CreatedBy`, `UseraccountID`, `ReportReadyID`, `DateCreated`, `InitiatedDate`, `ActualCompletedDate`, `ProjectedCompletedDate`, `CheckpackagesID`, `Alacartepackage1`, `Alacartepackage2`, `OperatorID`, `Status`, `caseRef`) VALUES
(1, 43, 70, NULL, '2011-07-22 02:29:31', '2011-07-07 07:27:44', '2011-07-22 02:29:31', '2011-07-17 06:53:52', 11, NULL, NULL, 44, 6, ''),
(2, 43, 74, NULL, '2012-04-03 04:17:15', '2011-07-11 07:07:23', '2011-07-13 05:32:58', '2011-07-21 07:01:34', 20, 0, 0, 51, 0, ''),
(3, 43, 75, NULL, '2011-07-29 04:10:07', '2011-07-11 07:27:12', '2011-07-29 04:10:07', '2011-07-21 07:02:14', 20, NULL, NULL, 45, 6, ''),
(4, 43, 78, NULL, '2011-07-18 03:32:27', '2011-07-11 07:51:31', '2011-07-13 02:18:34', '2011-07-21 07:37:53', 20, NULL, NULL, 45, 6, ''),
(5, 43, 76, NULL, '2011-07-29 04:09:19', '2011-07-11 07:51:11', '2011-07-29 04:09:19', '2011-07-21 07:38:30', 20, NULL, NULL, 45, 6, ''),
(6, 43, 77, NULL, '2011-07-18 03:32:49', '2011-07-11 07:51:34', '2011-07-18 02:18:46', '2011-07-21 07:39:00', 20, NULL, NULL, 45, 6, ''),
(7, 43, 79, NULL, '2011-07-18 03:33:02', '2011-07-11 07:53:24', '2011-07-18 01:50:12', '2011-07-21 07:42:57', 20, NULL, NULL, 45, 6, ''),
(8, 43, 80, NULL, '2011-07-29 04:10:38', '2011-07-11 07:53:58', '2011-07-29 04:10:38', '2011-07-21 07:43:14', 20, NULL, NULL, 45, 6, ''),
(9, 43, 81, NULL, '2011-07-18 03:31:54', '2011-07-11 07:53:49', '2011-07-13 02:17:02', '2011-07-21 07:43:43', 20, NULL, NULL, 45, 6, ''),
(11, 43, 88, NULL, '2011-07-18 03:15:53', '2011-07-13 04:57:38', '2011-07-15 08:57:15', '2011-07-23 04:39:14', 12, NULL, NULL, 44, 6, ''),
(13, 43, 90, NULL, '2011-07-26 07:39:24', '2011-07-13 12:16:48', '2011-07-26 07:39:24', '2011-07-23 12:13:50', 15, NULL, NULL, 51, 6, ''),
(63, 43, 176, NULL, '2011-09-13 08:23:13', '2011-08-26 10:00:32', '2011-09-13 08:23:13', '2011-09-05 09:58:47', 41, NULL, NULL, 45, 6, ''),
(62, 43, 174, NULL, '2011-08-24 03:54:30', '2011-08-24 03:53:13', '2011-08-24 03:54:30', '2011-08-29 03:52:48', 17, NULL, NULL, 51, 6, ''),
(61, 43, 173, NULL, '2011-08-24 03:55:05', '2011-08-24 03:53:39', '2011-08-24 03:55:05', '2011-08-29 03:52:36', 17, NULL, NULL, 51, 6, ''),
(60, 43, 172, NULL, '2011-08-24 03:22:41', '2011-08-24 03:21:50', '2011-08-24 03:22:41', '2011-08-29 03:21:11', 17, NULL, NULL, 51, 6, ''),
(59, 43, 171, NULL, '2011-08-24 03:23:19', '2011-08-24 03:22:00', '2011-08-24 03:23:19', '2011-08-29 03:20:57', 17, NULL, NULL, 51, 6, '');
You might want to try this:
Count the number of working days (took it from here)
SELECT 5 * (DATEDIFF('2012-12-31', '2012-01-01') DIV 7) + MID('0123444401233334012222340111123400012345001234550', 7 * WEEKDAY('2012-01-01') + WEEKDAY('2012-12-31') + 1, 1)
This gives you 261 working days for 2012.
Now you need to know your holidays that are not on a weekend
SELECT COUNT(*) FROM holidays WHERE DAYOFWEEK(holiday) < 6
The result of this depends on your holiday table.
We need to get that in one query:
SELECT 5 * (DATEDIFF('2012-12-31', '2012-01-01') DIV 7) + MID('0123444401233334012222340111123400012345001234550', 7 * WEEKDAY('2012-01-01') + WEEKDAY('2012-12-31') + 1, 1) - (SELECT COUNT(*) FROM holidays WHERE DAYOFWEEK(holiday) < 6)
This should be it.
Edit: Please be aware that this only works properly if your end date is higher than your start date.
Create a table that contains all the weekends and holidays for the next 100whatever years.
You need to be able to specify when a day is a 'holiday' given that no one knows what the holidays will be for 2052 yet, you will not be able to make an accurate function at this time anyway. just update your non-work day table each year when the holidays become known (but you will always know the weekends).
Then your query becomes:
SELECT DATEFIFF(end_date, start_date) - COALESCE((SELECT COUNT(1) FROM nonWorkDays WHERE nonWorkDays.date BETWEEN start_date AND end_date), 0)
FROM accounts
If you really need to write a DATEDIFFWITHOUTWEEKENDSORHOLIDAYS function then just use the above and create a function (there's plenty of resources on how to make functions in each RDBMS).. just be sure to give it a better name. ^_^
One thing you will need to fix is I think there's a +1 missing somewhere in the above, for example DATEDIFF(today, today) if today is a weekend will return -1 instead of returning 0.
Something like this may work. Add all holiday dates and weekend dates to a table.
SELECT
DATEDIFF(end_date, start_date)
FROM table
WHERE date NOT IN (SELECT date FROM holidaydatestable )
Try This Code this will Calculate no of days Excluding Weekends
SELECT
(DATEDIFF(dd, #StartDate, #EndDate)+1)
-(DATEDIFF(wk, #StartDate, #EndDate) * 2)
from test_tbl where date NOT IN (SELECT date FROM holidaydatestable )
Make a function that will make a while cycle between the dates incrementing the number of days when it's not a saturday or sunday.