SQL Server Conditional Count Issue - sql

I am trying to do something apparently simple in sql server but not been able to achieve the desired result yet (I am of course not a sql expert).
My source table:
And I am trying to get the output like below:
I have tried to give the field names meaningful so that the problem becomes self explanatory. I haven't been able to generate the 3rd column of the desired output yet.
Please can someone help??
Thanks & Regards.

You can try below -
select date,count(*) as idcount,count(case when status='Pass' then 1 end) as idpassed
from tablname
group by date

Try this:
Declare #t table( dates varchar(50),id int,status varchar(50))
insert into #t values ('2019/8',1,'Pass')
insert into #t values ('2019/9',1,'fail')
insert into #t values ('2019/9',2,'fail')
insert into #t values ('2019/8',3,'fail')
select dates,count(id) idcount,sum(case when status='pass' then 1 else 0 end) as pascount from #t
group by dates

Related

Get every string before character in SQL Server

I got two record in table which is as below -:
1.123-21
2.123-21-30
How to query for all string before certain place of character . Below shown expected output
1. 123-21 -> 123
2. 123-21-30 ->123-21
How can I solve it?
DECLARE #T TABLE (Vals VARCHAR(100))
INSERT INTO #T(Vals) VALUES ('123-21') , ('123-21-30')
SELECT LEFT(Vals, LEN(Vals) - CHARINDEX('-', REVERSE(Vals)) )
FROM #T

Easiest way to query a SQL Server 2008 R2 XML data type?

I need to get a node value in an XML data type column.
<CustomContentData>
<prpIsRSSFeed>false</prpIsRSSFeed>
</CustomContentData>
How is this done in SQL Server?
The column name is ClassXML
Use XQuery, a simple example with your data would be:
DECLARE #T TABLE (ClassXML XML);
INSERT #T (ClassXML)
VALUES ('<CustomContentData>
<prpIsRSSFeed>false</prpIsRSSFeed>
</CustomContentData>');
SELECT t.ClassXML.value('CustomContentData[1]/prpIsRSSFeed[1]', 'VARCHAR(5)')
FROM #T AS t;
If the column is already XML data type in SQL Server, then the code below should work by using the value function with XPATH. If it's stored as a varchar, you'd just need to replace ClassXML.value with CONVERT(XML, ClassXML).value. Hope this helps!
DECLARE #Data TABLE (ClassXML XML)
INSERT #Data VALUES ('<CustomContentData><prpIsRSSFeed>false</prpIsRSSFeed></CustomContentData>')
SELECT
CONVERT(BIT, CASE WHEN ClassXML.value ('(/CustomContentData/prpIsRSSFeed)[1]',
'VARCHAR(50)') = 'true' THEN 1 ELSE 0 END) AS IsRssFeed
FROM #Data
Yields output
IsRssFeed
---------
0

If parameter is null, pull results from table

This might be a stupid question, but I haven't found a way to word this to get an answer that suits what I'm trying to accomplish. I might just be having a stupid moment.
I have an input variable for a sproc; that input variable may be passed in as null.
If the value is null, I would like insert into a temp table a list of values from another table. Otherwise, I'd just like to insert into the temple table the value of the parameter.
What I'm trying to do is something like this
INSERT INTO #tempTable
SELECT (CASE WHEN #myVariable IS NULL
THEN (SELECT [myVariable] FROM myTable)
ELSE #myVariable END)
This won't work because that select statement pulls back a large number of results (and it's malformed), but that's the general idea. I basically want to have an optional parameter where the user can specify a specific ID, or get back ALL the IDs.
Does anyone have any suggestions on the best way to go about this?
Thank you!
I think this UNION will do
INSERT INTO #tempTable
SELECT #myVariable WHERE #myVariable IS NOT NULL
UNION
SELECT [myVariable] FROM myTable WHERE #myVariable IS NULL
Of course if it doesn't need to be one query - you can use simple IF logic
IF #myVariable IS NULL
INSERT INTO #tempTable
SELECT [myVariable] FROM myTable
ELSE
INSERT INTO #tempTable
SELECT #myVariable
Would something like this work for you?
SELECT DISTINCT ISNULL(#myVariable, myVariableColumn)
FROM myTable
I suggest this query:
INSERT INTO #tempTable
SELECT CASE WHEN #myVariable IS NULL Then [myVariable] else #myVariable end FROM myTable

SQL Command to execute multiple times?

I have situations that I need to write multiple rows of the same value to setup some tables. Say I have to add 120 rows with two columns populated. I am looking for a shortcut, instead of having the Insert line repeated n times. How to do this?
In SQL Server Management Studio, you can use the "GO" keyword with a parameter:
INSERT INTO YourTable(col1, col2, ...., colN)
VALUES(1, 'test', ....., 25)
GO 120
But that works only in Mgmt Studio (it's not a proper T-SQL command - it's a Mgmt Studio command word).
Marc
How about
Insert Table( colsnames )
Select Top 120 #value1, #Value2, etc.
From AnyTableWithMoreThan120Rows
Just make sure the types of the values in the #Value list matches the colNames List
what about
insert into tbl1
(col1,col2)
(select top 120 #value1,#value2 from tbl2)
if in sql server 2008 . new in sql server 2008 to insert into a table multiple rows in a single query .
insert into tbl1
(col1,col2)
values
(#value1,#value2),(#value1,#value2),.....(#value1,#value2)
Put the values in an unused table for safe keeping. From there you can insert from this table to the tables you need to setup.
Create an Excel Spreadsheet with your data.
Import the speadsheet into Sql Server.
You can even try with something like this(just an example)
declare #tbl table(col1 varchar(20),col2 varchar(20))
; with generateRows_cte as
(
select
1 as MyRows
union all
select
MyRows+1
from generateRows_cte
where MyRows < 120
)
insert into #tbl(col1,col2)
select
'col1' + CAST(MyRows as varchar),'col2' + CAST(MyRows as varchar)
from generateRows_cte OPTION (MAXRECURSION 0)
select * from #tbl
Note:- Why not you are trying with Bulk insert into SqlServer from a dataset ? I didnot notice first that u have a front end too(VB)!

Concatenating records in a single column without looping?

I have a table with 1 column of varchar values. I am looking for a way to concatenate those values into a single value without a loop, if possible. If a loop is the most efficient way of going about this, then I'll go that way but figured I'd ask for other options before defaulting to that method. I'd also like to keep this inside of a SQL query.
Ultimately, I want to do the opposite of a split function.
Is it possible to do without a loop (or cursor) or should I just use a loop to make this happen?
Edit:
Since there was a very good answer associated with how to do it in MySql (as opposed to MS Sql like I initially intended), I decided to retag so others may be able to find the answer as well.
declare #concat varchar(max)
set #concat = ''
select #concat = #concat + col1 + ','
from tablename1
try this:
DECLARE #YourTable table (Col1 int)
INSERT INTO #YourTable VALUES (1)
INSERT INTO #YourTable VALUES (2)
INSERT INTO #YourTable VALUES (30)
INSERT INTO #YourTable VALUES (400)
INSERT INTO #YourTable VALUES (12)
INSERT INTO #YourTable VALUES (46454)
SELECT
STUFF(
(
SELECT
', ' + cast(Col1 as varchar(30))
FROM #YourTable
WHERE Col1<=400
ORDER BY Col1
FOR XML PATH('')
), 1, 2, ''
)
OUTPUT:
-------------------
1, 2, 12, 30, 400
(1 row(s) affected)
I just tackled a problem like this and looping took forever. So, I concantenated the values in the presentation medium (in this case Crystal Reports) and it was very fast.
Just an idea.
If it is MySQL, you can use GROUP_CONCAT
SELECT a, GROUP_CONCAT(b SEPARATOR ',') FROM table GROUP BY a;
Probably dated now but check out Adam Machanic's post on the topic.
And this one is certainly dated; I wrote it in 2004.
Why do I prefer a function over "keeping it inside a SQL query"? Because you'll probably have to do this more than once. Why not encapsulate that code into a single module instead of repeating it all over the place?