how to use coalesce with in, in the where part - sql-server

How to use Coalesce Command in the following code
PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
in this code
SELECT DISTINCT
[dbo].[test2](A.PIECE_DETAIL ) TOTAL_QUANTITY,
PIECE_LATIN = (SELECT PIECE_LATIN FROM PIECES WHERE PIECE_ID =
(SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_LATIN = (SELECT BRAND_LATIN FROM BRANDS WHERE BRAND_ID =
(SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_ID = (SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_ID = (SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
MODEL_NAME = (SELECT MODEL_NAME FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_DETAIL MODEL_ID,
A.PIECE_STATUS ,
PIECE_STATUS_Name = (SELECT STATUS_Name FROM PIECE_STATUS WHERE STATUS_ID = A.PIECE_STATUS) ,
A.PIECE_DETAIL
FROM DOCUMENT_ITEMS A
WHERE
PIECE_STATUS = 1 and
DOC_SEQ IN (SELECT DOC_SEQ FROM DOCUMENT_HEADER WHERE DOC_TYPE IN (1,3))
AND PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
AND [DBO].[GET_WAREHOUSE_QUANTITIES_SPECIAL_ID_EXIST](A.PIECE_DETAIL ,A.SPECIAL_ID )> 0
GROUP BY PIECE_DETAIL ,SPECIAL_ID ,PIECE_STATUS
thanks all

Something like this then:
WHERE PIECE_DETAIL IN
(
SELECT
coalesce(PIECE_DETAIL,B.MODEL_ID)
FROM
PIECES_DETAILS B
WHERE
PIECE_ID = #PIECE_ID
AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID)
)
Edit
Maybe something like this:
WHERE
(
(
FROM_DATE IS NULL AND TO_DATE IS NULL
)
OR
(
BUY_DOC_DATE BETWEEN FROM_DATE AND TO_DATE
)
)

Related

convert SQL server query to snowflake , i need help in calling local variable using javascript

# sql server query:#
CREATE FUNCTION [dbo].[fnCurrencyExchange]
(#ExchngType NVARCHAR(30),
#InCurrMode NVARCHAR(10),
#OutCurMode NVARCHAR(10),
#InDate DATE)
RETURNS DECIMAL(17, 6)
BEGIN
DECLARE #lExchangeRate DECIMAL(17, 7);
DECLARE #2ExchangeRate DECIMAL(17, 7);
DECLARE #3ExchangeRate DECIMAL(17, 7);
DECLARE #4ExchangeRate DECIMAL(17, 7);
DECLARE #currdate NVARCHAR(30);
IF ISNULL(#ExchngType,'') = '' -- Default use Balance Sheet Exchnage rate
SET #ExchngType = 'Income Statement';
IF ( #InCurrMode = #OutCurMode AND #InCurrMode IS NOT NULL AND #OutCurMode IS NOT NULL )
RETURN 1;
IF #InDate = ''
SET #currdate = getDate();
Else
SET #currdate = #InDate;
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #InCurrMode
AND a.ToCurrency = #OutCurMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #lExchangeRate IS NOT NULL
RETURN #lExchangeRate;
IF #lExchangeRate IS NULL
BEGIN
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #OutCurMode
AND a.ToCurrency = #InCurrMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
END
IF #lExchangeRate IS NOT NULL
RETURN ( 1 / #lExchangeRate );
IF #lExchangeRate IS NULL
BEGIN
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #InCurrMode
AND a.ToCurrency = 'USD'
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #lExchangeRate IS NULL
SELECT TOP 1 #lExchangeRate = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = 'USD'
AND a.ToCurrency = #InCurrMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
SELECT TOP 1 #2ExchangeRate = exchangerate
FROM (SELECT a.ExchangeRate ExchangeRate,
Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #OutCurMode
AND a.ToCurrency = 'USD'
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #2ExchangeRate IS NULL
SELECT TOP 1 #2ExchangeRate = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a.ExchangeRate ExchangeRate,
Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = 'USD'
AND a.ToCurrency = #OutCurMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
SELECT #3ExchangeRate = ( #lExchangeRate / #2ExchangeRate );
END
RETURN Isnull(#3ExchangeRate, 0);
END
convert this into snowflake , need help on this on?
i tried but i was unsuccessful
CREATE OR REPLACE FUNCTION "fn_FncurrencyExchange"("ExchngType" NVARCHAR(30),"InCurrMode" NVARCHAR(10),"OutCurMode" NVARCHAR(10),"InDate" DATE)
RETURNS NUMBER(17,6)
LANGUAGE JAVASCRIPT
COMMENT='Create Date: 2022-11-25 Author: Performalytic Team '
AS '
var lExchangeRate =p1;
var 2ExchangeRate =p2;
var 3ExchangeRate =p3;
var 4ExchangeRate =p4;
var currdate =p5;
IF (ISNULL(ExchngType,'') = '' )
{ ExchngType = ''Income Statement'';
}
IF ( InCurrMode = OutCurMode AND InCurrMode IS NOT NULL AND OutCurMode IS NOT NULL )
RETURN 1;
IF InDate = ''
{ p5 = CURRENT_DATE();
}
Else
{ p5 = InDate;
}
SELECT p1 = ExchangeRate
FROM (
SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = InCurrMode
AND a."ToCurrency" = OutCurMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
IF p1 IS NOT NULL
RETURN p1;
IF p1 IS NULL
BEGIN
SELECT p1 = ExchangeRate
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = OutCurMode
AND a."ToCurrency" = InCurrMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
END
IF p1 IS NOT NULL
RETURN ( 1 / p1 );
IF p1 IS NULL
BEGIN
SELECT p1 = ExchangeRate
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = InCurrMode
AND a."ToCurrency" = ''USD''
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
IF p1 IS NULL
SELECT p1 = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = ''USD''
AND a."ToCurrency" = InCurrMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
SELECT p2 = exchangerate
FROM (SELECT a."ExchangeRate" ExchangeRate,
Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = OutCurMode
AND a."ToCurrency" = ''USD''
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
END
IF p2 IS NULL
BEGIN
SELECT p2 = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a."ExchangeRate" ExchangeRate,
Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = ''USD''
AND a."ToCurrency" = OutCurMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
SELECT p3 = ( p1 / p2 );
END
RETURN ISNULL(p3, 0);
END
;`;
You set the language to JavaScript, you started with JS commands but you try to run SQLs directly. It is also defined as UDF, in this case you can't call SQLs from JavaScript.
Do you need to create a UDF? Then check this one: https://docs.snowflake.com/en/developer-guide/udf/sql/udf-sql.html
If you want conditionals etc, and run SQL directly, consider SQL scripting (but it will be a stored procedure): https://docs.snowflake.com/en/developer-guide/snowflake-scripting/index.html
You may also want to check writing Stored Procedures in JavaScript: https://docs.snowflake.com/en/sql-reference/stored-procedures-javascript.html

Convert SQL query to Linq2db

Some one help me to convert SQL query to linq2db join query.
Below is my query.
var query = from a in _accountRepository.Table
join b in _documentRepository.Table on a.ID equals b.AccountID
join c in _documentTypeRepository.Table on b.DocumentTypeID equals c.ID
where a.CompanyID == companyID && b.CompanyID == companyID
&& c.CompanyID == companyID
&& a.IsActive && !a.IsDeleted && c.IsInvoice
&& b.IsActive && !b.IsDeleted
&& b.Date.Date >= fromDate.Date && b.Date.Date <=
toDate.Date
&& (b.AccountID == accountID || accountID == null)
&& (costcenterID.Contains(b.CostCenterID) || costcenterID == null)
&& a.AccountTypeID == (int)DefaultAccountTypes.Customer
group b by new { a.DisplayName, a.ID } into g
select new SalesByCustomerModel
{
AccountID = g.Key.ID,
DisplayName = g.Key.DisplayName,
InvoiceCount = g.Count(),
Sales = g.Sum(x => (x.SubTotal - x.Discount)),
SalesWithTax = g.Sum(x => x.Total),
Tax = g.Sum(x => x.Tax)
};
I have to add this. How can I achive with linq2db.
INNER JOIN ( SELECT ROW_NUMBER() OVER(PARTITION by DocumentID ORDER BY DocumentID) AS SrNo,
DocumentID
FROM DocumentDetail
WHERE (DocumentItemID = #itemID OR #itemID IS NULL)
AND CompanyID = #companyID ) D ON D.DocumentID = B.ID AND SrNo = 1
Linq2db supports window functions, and we can write details subquery and add join:
var details =
from d in _documentDetailRepository.Table
where (d.DocumentItemID == itemID || itemID == null)
&& d.CompanyID == companyID
select new
{
d.DocumentID,
SrNo = Sql.Ext.RowNumber().Over()
.PartitionBy(d.DocumentID)
.OrderBy(d.DocumentID)
.ToValue()
};
// Then your query can be extended
var query =
from a in _accountRepository.Table
join b in _documentRepository.Table on a.ID equals b.AccountID
join d in details on new { DocumentID = b.Id, SrNo = 1 } equals new { d.DocumentID, d.SrNo }
...

Sql Server View : Conversion failed when converting the varchar value 'No PhysicalAttributeID' to data type int

So I have created a view, but I seem to be getting an error I do not seem to understand why, I am just assigning the value, I am posting the code here
SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN commodityid = 1 THEN 0 ELSE 1 END) AS ID,
CommodityID,
CommodityName,
SubCommodityID,
SubCommodityName,
SectorID,
Sector,
GroupID,
GroupName,
StatisticID,
StatisticType,
SourceID,
Source,
SourceDescription,
PhysicalAttributeID,
PhysicalAttribute,
UtilizationID,
UtilizationPractice,
ProductionPracticeID,
ProductionPractice,
Description,
SourceSeriesID,
TimeID,
TimeFrequency,
Date,
GeographyID,
GeographyType,
City,
County,
State,
Region,
Country,
UnitID,
Unit,
LifecyclePhaseID,
LifecyclePhaseDescription AS Value
FROM (SELECT DISTINCT
dv.ERSDataValues_ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
cds.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
su.ERSSector_ID AS SectorID,
su.ERSSector_Desc AS Sector,
gu.ERSGroup_ID AS GroupID,
gu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
phlu.ERSPhysicalAttribute_ID AS PhysicalAttributeID,
cds.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
upu.ERSUtilPractice_ID AS UtilizationID,
upu.ERSUtilPractice_Desc AS UtilizationPractice,
pu.ERSProdPractice_ID AS ProductionPracticeID,
pu.ERSProdPractice_Desc AS ProductionPractice,
CASE
WHEN cds.ERSCommodity_SourceSeriesID_LongDesc IS NULL THEN 'No Description'
ELSE cds.ERSCommodity_SourceSeriesID_LongDesc
END AS Description,
CASE
WHEN cds.ERSCommodity_SourceSeriesID IS NULL THEN 'No SourceSeriesID'
ELSE cds.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdt.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tu.ERSTimeDimension_Date AS Date,
gdu.ERSGeographyDimension_ID AS GeographyID,
gtu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
dv.ERSDataValues_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
dv.ERSDataValues_AttributeValue AS Value
FROM CoSD.ERSCommodityDataSeries cds
INNER JOIN cosd.ERSPhysicalAttribute_LU phlu ON phlu.ERSPhysicalAttribute_ID = cds.ERSCommodity_ERSPhysicalAttribute_ID
INNER JOIN CoSD.ERSDataValues dv ON cds.ERSCommodity_ID = dv.ERSDataValues_ERSCommodity_ID
INNER JOIN CoSD.ERSSector_LU su ON cds.ERSCommodity_ERSSector_ID = su.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU gu ON cds.ERSCommodity_ERSGroup_ID = gu.ERSGroup_ID
INNER JOIN CoSD.ERSProdPractice_LU pu ON cds.ERSCommodity_ERSProdPractice_ID = pu.ERSProdPractice_ID
INNER JOIN CoSD.ERSUtilPractice_LU upu ON cds.ERSCommodity_ERSUtilPractice_ID = upu.ERSUtilPractice_ID
AND cds.ERSCommodity_ERSUtilPractice_ID = upu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSUnit_LU ulu ON dv.ERSDataValues_ERSUnit_ID = ulu.ERSUnit_ID
INNER JOIN CoSD.ERSSource_LU slu ON cds.ERSCommodity_ERSSource_ID = slu.ERSSource_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON cds.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSTimeDimension_LU tu ON dv.ERSDataValues_ERSTimeDimension_ID = tu.ERSTimeDimension_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdu ON dv.ERSDataValues_ERSGeography_ID = gdu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSTimeDimensionType_LU tdt ON tu.ERSTimeDimension_TimeDimensionType_ID = tdt.ERSTimeDimensionType_ID
INNER JOIN CoSD.ERSGeographyType_LU gtu ON gdu.ERSGeographyDimension_ERSGeographyType_ID = gtu.ERSGeographyType_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON csc.ERSCommoditySubCommodity_ID = cds.ERSCommoditySubCommodity_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = dv.ERSDataValues_DataRowLifecyclePhaseID
WHERE dv.ERSDataRowPrivacy_ID = 1
AND dv.ERSDataValues_AttributeValue IS NOT NULL
UNION ALL
SELECT DISTINCT
cds.ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
csc.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
slu.ERSSector_ID AS SectorID,
slu.ERSSector_Desc AS Sector,
glu.ERSGroup_ID AS GroupID,
glu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
selu.ERSSource_ID AS SourceID,
cvo.ERSConstructedVariable_InputSources AS Source,
selu.ERSSource_LongDesc AS SourceDescription,
cds.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID,
cds.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
ulu.ERSUtilPractice_ID AS UtilizationID,
ulu.ERSUtilPractice_Desc AS UtilizationPractice,
plu.ERSProdPractice_ID AS ProductionPracticeID,
plu.ERSProdPractice_Desc AS ProductionPractice,
cvo.ERSConstructedVariable_OutputName AS Description,
CASE
WHEN cds.ERSCommodity_SourceSeriesID LIKE '%(N%' THEN 'No SourceSeriesID'
ELSE cds.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
cvo.ERSConstructedVariable_TimeDimensionDate AS Date,
gdlu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdlu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdlu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdlu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdlu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdlu.ERSGeographyDimension_Country
END AS Country,
unlu.ERSUnit_ID AS UnitID,
unlu.ERSUnit_Desc AS Unit,
cvo.ERSConstructedVariable_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
cvo.ERSConstructedVariable_OutputValue AS Value
FROM CoSD.ERSConstructedVariablesOutcomes cvo
INNER JOIN CoSD.ERSCommodityDataSeries cds ON cvo.ERSConstructedVariable_NewDataSeriesID = cds.ERSCommodity_ID
INNER JOIN CoSD.ERSSector_LU slu ON cds.ERSCommodity_ERSSector_ID = slu.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU glu ON cds.ERSCommodity_ERSGroup_ID = glu.ERSGroup_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON cds.ERSCommoditySubCommodity_ID = csc.ERSCommoditySubCommodity_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON cds.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSUtilPractice_LU ulu ON cds.ERSCommodity_ERSUtilPractice_ID = ulu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSProdPractice_LU plu ON cds.ERSCommodity_ERSProdPractice_ID = plu.ERSProdPractice_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdlu ON cvo.ERSConstructedVariable_OutputGeographyDimensionID = gdlu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSUnit_LU unlu ON cvo.ERSConstructedVariable_OutputUnitID = unlu.ERSUnit_ID
INNER JOIN CoSD.ERSGeographyType_LU gtlu ON gdlu.ERSGeographyDimension_ERSGeographyType_ID = gtlu.ERSGeographyType_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = cvo.ERSConstructedVariable_TimeDimensionID
AND tlu.ERSTimeDimension_Date = cvo.ERSConstructedVariable_TimeDimensionDate
AND YEAR(tlu.ERSTimeDimension_Date) = YEAR(cvo.ERSConstructedVariable_TimeDimensionDate)
AND MONTH(tlu.ERSTimeDimension_Date) = MONTH(ERSConstructedVariable_TimeDimensionDate)
INNER JOIN cosd.ERSTimeDimensionType_LU tdlu ON tdlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSSource_LU selu ON cvo.ERSConstructedVariable_InputSourceID = selu.ERSSource_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = cvo.ERSConstructedVariable_DataRowLifecyclePhaseID
WHERE cvo.ERSConstructedVariable_DataRowPrivacyID = 1
AND cvo.ERSConstructedVariable_NewDataSeriesID IS NOT NULL
AND cvo.ERSConstructedVariable_OutputValue IS NOT NULL
UNION ALL
SELECT DISTINCT
CDS.ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
csc.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
slu.ERSSector_ID AS SectorID,
slu.ERSSector_Desc AS Sector,
glu.ERSGroup_ID AS GroupID,
glu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
selu.ERSSource_ID AS SourceID,
cvo.ERSConstructedVariable_InputSources AS Source,
selu.ERSSource_LongDesc AS SourceDescription,
CDS.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID,
CDS.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
ulu.ERSUtilPractice_ID AS UtilizationID,
ulu.ERSUtilPractice_Desc AS UtilizationPractice,
plu.ERSProdPractice_ID AS ProductionPracticeID,
plu.ERSProdPractice_Desc AS ProductionPractice,
cvo.ERSConstructedVariable_OutputName AS Description,
CASE
WHEN CDS.ERSCommodity_SourceSeriesID IS NULL THEN 'No SourceSeriesID'
ELSE CDS.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
cvo.ERSConstructedVariable_TimeDimensionDate AS Date,
gdlu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdlu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdlu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdlu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdlu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdlu.ERSGeographyDimension_Country
END AS Country,
unlu.ERSUnit_ID AS UnitID,
unlu.ERSUnit_Desc AS Unit,
cvo.ERSConstructedVariable_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
cvo.ERSConstructedVariable_OutputValue AS Value
FROM CoSD.ERSConstructedVariablesOutcomes cvo
INNER JOIN CoSD.ERSBusinessLogic BL ON cvo.ERSConstructedVariable_BusinessLogicID = BL.ERSBusinessLogic_ID
INNER JOIN cosd.ERSCommodityDataSeries CDS ON CDS.ERSCommodity_ID = BL.ERSBusinessLogic_InputDataSeries
INNER JOIN CoSD.ERSSector_LU slu ON CDS.ERSCommodity_ERSSector_ID = slu.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU glu ON CDS.ERSCommodity_ERSGroup_ID = glu.ERSGroup_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON CDS.ERSCommoditySubCommodity_ID = csc.ERSCommoditySubCommodity_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON CDS.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSUtilPractice_LU ulu ON CDS.ERSCommodity_ERSUtilPractice_ID = ulu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSProdPractice_LU plu ON CDS.ERSCommodity_ERSProdPractice_ID = plu.ERSProdPractice_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdlu ON cvo.ERSConstructedVariable_OutputGeographyDimensionID = gdlu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSUnit_LU unlu ON cvo.ERSConstructedVariable_OutputUnitID = unlu.ERSUnit_ID
INNER JOIN CoSD.ERSGeographyType_LU gtlu ON gdlu.ERSGeographyDimension_ERSGeographyType_ID = gtlu.ERSGeographyType_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = cvo.ERSConstructedVariable_TimeDimensionID
AND tlu.ERSTimeDimension_Date = cvo.ERSConstructedVariable_TimeDimensionDate
AND YEAR(tlu.ERSTimeDimension_Date) = YEAR(cvo.ERSConstructedVariable_TimeDimensionDate)
AND MONTH(tlu.ERSTimeDimension_Date) = MONTH(ERSConstructedVariable_TimeDimensionDate)
INNER JOIN cosd.ERSTimeDimensionType_LU tdlu ON tdlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSSource_LU selu ON cvo.ERSConstructedVariable_InputSourceID = selu.ERSSource_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = cvo.ERSConstructedVariable_DataRowLifecyclePhaseID
WHERE cvo.ERSConstructedVariable_DataRowPrivacyID = 1
AND BL.ERSBusinessLogic_InputsCount = 1
AND BL.ERSBusinessLogic_InputDataSeries NOT LIKE '%CV%'
AND cvo.ERSConstructedVariable_NewDataSeriesID IS NULL
AND cvo.ERSConstructedVariable_OutputValue IS NOT NULL
UNION ALL
SELECT DISTINCT
'-1' AS CommodityID,
ERSMacro_Desc AS CommodityName,
'-1' AS SubCommodityID,
ERSMacro_LongDesc AS SubCommodityName,
'4' AS SectorID,
'Macro' AS Sector,
'17' AS GroupID,
'Macro' AS GroupName,
NULL AS StatisticID,
'No StatisticType' AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
TRY_CONVERT(varchar, 'No PhysicalAttributeID') AS PhysicalAttributeID,
'No PhysicalAttribute' AS PhysicalAttribute,
'No UtilizationID' AS UtilizationID,
'No UtilizationPractice' AS UtilizationPractice,
'No ProductionPracticeID' AS ProductionPracticeID,
'No ProductionPractice' AS ProductionPractice,
'No Description' AS Description,
'No SourceSeriesID' AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(ttlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tlu.ERSTimeDimension_Date AS Date,
glu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE glu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE glu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE glu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE glu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE glu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
'No LifecyclephaseID' AS LifecyclePhaseID,
'No LifecyclePhaseDescription' AS LifecyclePhaseDescription,
mlu.ERSMacro_Value AS Value
FROM cosd.ERSMacro_LU mlu
INNER JOIN cosd.ERSSource_LU slu ON slu.ERSSource_ID = mlu.ERSMacro_Source_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = mlu.ERSMacro_TimeDimension_ID
INNER JOIN cosd.ERSTimeDimensionType_LU ttlu ON ttlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSGeographyDimension_LU glu ON glu.ERSGeographyDimension_ID = mlu.ERSMacro_GeographyDimension_ID
INNER JOIN cosd.ERSGeographyType_LU gtlu ON gtlu.ERSGeographyType_ID = glu.ERSGeographyDimension_ERSGeographyType_ID
INNER JOIN cosd.ERSUnit_LU ulu ON ulu.ERSUnit_ID = mlu.ERSMacro_Unit_ID) derived;
I get this error :
Conversion failed when converting the varchar value 'No PhysicalAttributeID' to data type int.
But the best part is if I run the last part of the code as below
SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN CommodityID = 1 THEN 0 ELSE 1 END) AS ID,
CommodityID,
CommodityName,
SubCommodityID,
SubCommodityName,
SectorID,
Sector,
GroupID,
GroupName,
StatisticID,
StatisticType,
SourceID,
Source,
SourceDescription,
PhysicalAttributeID,
PhysicalAttribute,
UtilizationID,
UtilizationPractice,
ProductionPracticeID,
ProductionPractice,
Description,
SourceSeriesID,
TimeID,
TimeFrequency,
Date,
GeographyID,
GeographyType,
City,
County,
State,
Region,
Country,
UnitID,
Unit,
LifecyclePhaseID,
LifecyclePhaseDescription,
Value
FROM (SELECT DISTINCT
'-1' AS CommodityID,
ERSMacro_Desc AS CommodityName,
'-1' AS SubCommodityID,
ERSMacro_LongDesc AS SubCommodityName,
'4' AS SectorID,
'Macro' AS Sector,
'17' AS GroupID,
'Macro' AS GroupName,
'No Statistic' AS StatisticID,
'No StatisticType' AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
'No PhysicalAttributeID' AS PhysicalAttributeID,
'No PhysicalAttribute' AS PhysicalAttribute,
'No UtilizationID' AS UtilizationID,
'No UtilizationPractice' AS UtilizationPractice,
'No ProductionPracticeID' AS ProductionPracticeID,
'No ProductionPractice' AS ProductionPractice,
'No Description' AS Description,
'No SourceSeriesID' AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(ttlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tlu.ERSTimeDimension_Date AS Date,
glu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE glu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE glu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE glu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE glu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE glu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
'No LifecyclephaseID' AS LifecyclePhaseID,
'No LifecyclePhaseDescription' AS LifecyclePhaseDescription,
mlu.ERSMacro_Value AS Value
FROM cosd.ERSMacro_LU mlu
INNER JOIN cosd.ERSSource_LU slu ON slu.ERSSource_ID = mlu.ERSMacro_Source_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = mlu.ERSMacro_TimeDimension_ID
INNER JOIN cosd.ERSTimeDimensionType_LU ttlu ON ttlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSGeographyDimension_LU glu ON glu.ERSGeographyDimension_ID = mlu.ERSMacro_GeographyDimension_ID
INNER JOIN cosd.ERSGeographyType_LU gtlu ON gtlu.ERSGeographyType_ID = glu.ERSGeographyDimension_ERSGeographyType_ID
INNER JOIN cosd.ERSUnit_LU ulu ON ulu.ERSUnit_ID = mlu.ERSMacro_Unit_ID) derived;
This runs perfectly without any problems. If I change 'No PhysicalAttributeID' to null, it runs properly, I have tried this solution and also this
I seem to be heading no where, any ideas ?
It is because in the first query column 15 is PhysicalAttributeID which is almost certainly an int. Then you attempt to use UNION ALL to your second query. It will attempt an implicit conversion and fail.
An easy solution would be to adjust the first query. You would need to something like on each of those queries.
PhysicalAttributeID = convert(varchar(20), PhysicalAttributeID)
This is the line you have error at:
TRY_CONVERT(varchar, 'No PhysicalAttributeID') AS PhysicalAttributeID
this is incompatible with its matches, like
phlu.ERSPhysicalAttribute_ID AS PhysicalAttributeID
or
cds.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID
or
CDS.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID
You will need to convert the numeric values above into varchar to solve your problem.

Boolean conditions in SQL where clause

I wanted to write an sql query to fetch data as:
1. when param = 'all' it should list data across the table
2. when param = 'yes' it should list data where invoicenumber is not empty.
3. when param = 'no' it should list data where invoicenumber is empty.
i tried below query for yes and no
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced = 'yes') or (InvoiceNumber = ''))
and
((#invoiced = 'no') or (InvoiceNumber <> ''))
now i also want to incorporate all condition, could anyone suggest how could i achieve that
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
#invoiced = 'all'
OR
(#invoiced = 'yes' AND InvoiceNumber <> '')
OR
(#invoiced = 'no' AND InvoiceNumber = '')
Try this
declare #invoiced as nvarchar(10) = 'no'
select
*
from OrderSummary
where
(
#invoiced = 'all'
OR
(
#invoiced = 'yes'
AND
InvoiceNumber <> ''
)
OR
(
#invoiced = 'no'
AND
InvoiceNumber = ''
)
)
It should fulfill your requirement.
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced in ('all','no')) OR (#invoiced = 'yes' AND InvoiceNumber <> ''))
and
((#invoiced in ('all','yes')) OR (#invoiced = 'no' AND InvoiceNumber = ''))
and
(#invoiced in ('no','yes'))
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced = 'yes') and (InvoiceNumber <> '') )
or
((#invoiced = 'no') and ( (InvoiceNumber = '') or (InvoiceNumber = null)))
or (#invoiced = 'all')
Please update this query with above query.

How to do this SQL in LINQ

Morning i would like to know how to do this bit of (MS) SQL in LINQ...
SELECT CONVERT(CHAR(10),orderDate,110) AS OrderDate,
SUM(1) AS TotalOrders
FROM Orders
WHERE OrderDate>getdate()-30
GROUP BY CONVERT(CHAR(10),orderDate,110)
ORDER BY OrderDate DESC
Many thanks in advance.
UPDATE
I ended using and edited version of the solutions provided below, thought i would share it...
using (DataDataContext dc = new DataDataContext())
{
var query = from o in dc.Orders
where o.orderDate > DateTime.Now.AddDays(-30)
let dt = o.orderDate
group o by new DateTime(dt.Year, dt.Month, dt.Day) into g
select new OrderCounts
{
OrderDate = String.Format("{0:d}", g.Key.Date),
TotalOrders = g.Count()
};
query.GroupBy(o => o.OrderDate);
query.OrderBy(o => o.OrderDate);
return query.ToList();
}
var result =(from s in Orders
where s.OrderDate > DateTime.Now.AddDays(-30)
group s by new { date = s.OrderDate.ToString() } into g
// or use ((DateTime)s.OrderDate).ToShortDateString() instead of s.OrderDate.ToString()
select new
{
OrderDate = g.Key.date,
TotalOrders = g.Count()
}).OrderByDescending(x=>x.OrderDate);;
The query will be
var query = from o in res
where o.OrderDate > DateTime.Now.AddDays(-30)
orderby o.OrderDate descending
group o by o.OrderDate into g
select new
{
OrderDate = g.Key.Date.ToString("MM/dd/yyyy")
,
TotalOrders = g.Sum(i=> 1)
};
OR by Lambda expression
var query= res
.Where(i => i.OrderDate > DateTime.Now.AddDays(-30))
.OrderByDescending(o => o.OrderDate)
.GroupBy(g => g.OrderDate)
.Select(s => new { OrderDate = s.Key.Date.ToString("MM/dd/yyyy"), TotalOrders = s.Sum(i => 1) });

Resources